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

时间:2016-04-18 13:35:44

标签: sql tsql stored-procedures sql-server-2014 sql-function

我使用的是SQL Server 2014,我有一个表Attendance。此表格包含2列AttdDateStatus。我想创建一个存储过程,返回两个日期AttdDatestatus之间的日期列表。如果AttdDate在此列表(日期列表)中,则状态应为true,否则状态应为false。

有什么建议吗?谢谢

2 个答案:

答案 0 :(得分:2)

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;

答案 1 :(得分:0)

您可以使用递归查询:

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 Server数据库中创建一个包含2100年所有可能日期的表格:

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