简体   繁体   中英

Get all dates between 2 dates in SQL Server stored procedure

I 'm using SQL Server 2014 and I have a table Attendance . This table has 2 columns AttdDate and Status . I want to create a stored procedure that returns list of dates between 2 dates, AttdDate and status . And if the AttdDate is in this list (dates list) status should be true else status should be 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:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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