prime prime - 7 months ago 19
SQL Question

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

Answer
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;
Comments