简体   繁体   English

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

[英]Get all dates between 2 dates in SQL Server stored procedure

I 'm using SQL Server 2014 and I have a table Attendance . 我正在使用SQL Server 2014,并且有一个表Attendance This table has 2 columns AttdDate and Status . 该表有2列AttdDateStatus I want to create a stored procedure that returns list of dates between 2 dates, AttdDate and status . 我想创建一个存储过程,该存储过程返回两个日期之间的日期列表,即AttdDatestatus And if the AttdDate is in this list (dates list) status should be true else status should be false. 如果AttdDate在此列表(日期列表)中,则状态应为true,否则状态应为false。

Any advice? 有什么建议吗? Thanks 谢谢

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;

You can use a recursive query for this: 您可以为此使用递归查询:

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

, however, its performance would be quite poor for longer ranges. 但是,对于更长的范围,其性能将很差。

I usually just create a table with all possible dates up to year 2100 in my SQL Server databases: 我通常只在SQL Server数据库中创建一个表,其中包含所有可能直到2100年的日期:

SELECT  *
FROM    dates
WHERE   d BETWEEN @mindate AND @maxdate

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM