How to Select records that don't exist in Sql Server

后端 未结 3 1027
醉梦人生
醉梦人生 2020-12-19 18:53

This isn\'t about checking if a record exists before selecting it, or viceversa.

The issue is this, I have a database with many records, they are stored by date, by

3条回答
  •  一个人的身影
    2020-12-19 19:12

    Eric Fan had the right idea, but I thought it might help to see an implementation:

    Here's a function that will return a table of the inclusive dates:

    CREATE FUNCTION dbo.fDatesBetween(@startDate Date, @endDate Date)
        RETURNS @tbl TABLE
            (
                a_date      Date
            )
    AS BEGIN
        DECLARE @thisDt Date
        SET @thisDt = @startDate
    
        WHILE @thisDt <= @endDate
        BEGIN
            INSERT INTO @tbl SELECT @thisDt
            SET @thisDt = DateAdd(day, 1, @thisDt)
        END
        RETURN
    END
    

    Now, if you do an outer join to your table from the function results, you will have what you are looking for:

    SELECT DATES.a_date, SampleTable.value1, SampleTable.value2
      FROM dbo.fDatesBetween(@startDate, @endDate) DATES
           LEFT JOIN SampleTable
              ON DATES.a_date = SampleTable.dt
    

    That should give you just what you asked for.

提交回复
热议问题