获取 SQL 服务器存储过程中 2 个日期之间的所有日期

Get all dates between 2 dates in SQL Server stored procedure

我正在使用 SQL Server 2014,并且我有一个 table Attendance。此 table 有 2 列 AttdDateStatus。我想创建一个存储过程,其中包含 returns 两个日期 AttdDatestatus 之间的日期列表。如果 AttdDate 在此列表(日期列表)中,则状态应为真,否则状态应为假。

有什么建议吗?谢谢

您可以为此使用递归查询:

WITH    q(d) AS
        (
        SELECT  @mindate
        UNION ALL
        SELECT  DATEADD(day, 1 d)
        FROM    q
        WHERE   d < @maxdate
        )
SELECT  *
FROM    q
OPTION  (MAXRECURSION 0)

,但是,对于更长的范围,它的性能会很差。

我通常只是在我的 SQL 服务器数据库中创建一个 table,其中包含所有可能的日期,直到 2100 年:

SELECT  *
FROM    dates
WHERE   d BETWEEN @mindate AND @maxdate
CREATE PROCEDURE sp_Attendance @Start DATETIME, @End DATETIME
AS
BEGIN 
    DECLARE @NumDays INT;
    -- This will give you the number of days between your start date and end date.
    SELECT @NumDays = DATEDIFF(DAY, @Start, @End) + 1;
    WITH CTE AS (
        SELECT TOP (@Numdays)
            /*
            ROW_NUMBER() OVER (ORDER BY a.object_id) will give you an integer from 1 to @NumDays becuase of TOP (@NumDays)
            ROW_NUMBER() OVER (ORDER BY a.object_id) - 1 will give you an integer from 0 to @NumDays
            DATEADD(DAY, ROW_NUMBER(), @Start) -- This will add the integer from the row number statement to your start date.
            i.e.
                @Start + 0
                @Start + 1
                @Start + 2
                etc
                etc
                @Start + @NumDays           
            */
            DATEADD(DAY, ROW_NUMBER() OVER (ORDER BY a.object_id) - 1, @Start) AS AttdDate
        FROM
            sys.all_columns a
        CROSS JOIN
            sys.all_columns b)
    SELECT
        c.AttdDate,
        CASE WHEN a.AttdDate IS NOT NULL THEN 1 ELSE 0 END AS Status
    FROM
        CTE c
    LEFT JOIN
        Attendance a
            ON c.AttdDate = a.AttdDate;
END;