How to return a default value when no rows are returned from the select statement

前端 未结 7 1883
庸人自扰
庸人自扰 2021-01-22 13:26

I have a select statement that returns two columns, a date column, and a count(value) column. When the count(value) column doesn\'t have any records,

7条回答
  •  遇见更好的自我
    2021-01-22 13:50

    Try this:

    DECLARE @Records TABLE (
        [RecordDate] DATETIME,
        [RecordCount] INT
    )
    
    DECLARE @Date DATETIME = '02/26/2014' -- Enter whatever date you want to start with
    DECLARE @EndDate DATETIME = '03/31/2014' -- Enter whatever date you want to stop
    WHILE (1=1)
    BEGIN
        -- Insert the date into the temp table along with the count
        INSERT INTO @Records (RecordDate, RecordCount) 
        VALUES (CONVERT(VARCHAR(25), @Date, 101), 
                (SELECT COUNT(*) FROM dbo.YourTable WHERE RecordDate = @Date))
    
        -- Go to the next day
        @Date = DATEADD(d, 1, @Date)
    
        -- If we have surpassed the end date, break out of the loop
        IF (@Date > @EndDate) BREAK;
    END
    
    SELECT * FROM @Records
    

    If your dates have time components, you would need to modify this to check for start and end of day in the SELECT COUNT(*)... query.

提交回复
热议问题