如何有效地循环使用Sql查询

时间:2015-02-02 16:14:39

标签: sql-server

我有FromTo约会。如下所示,

BeginDate                     End Date

1989-01-01 00:00:00.000       2015-12-31 00:00:00.000

我需要循环直到我获得这两个(开始和结束日期)记录之间所有日期的列表。我需要知道这样做的有效方法是什么。我不知道如何做到这一点。任何帮助都将受到高度赞赏。

由于

3 个答案:

答案 0 :(得分:2)

此方法使用生成的数字表,可能比循环更快。

DECLARE @BeginDate DATETIME = '19890101';
DECLARE @EndDate DATETIME = '20151231';

WITH 
    E1(N) AS ( SELECT 1 FROM ( VALUES (1),(1),(1),(1),(1),(1),(1),(1),(1),(1)) DT(N)),
    E2(N) AS ( SELECT 1 FROM E1 A, E1 B),
    E4(N) AS ( SELECT 1 FROM E2 A, E2 B),
    Numbers(N) AS
    (
        SELECT ROW_NUMBER() OVER ( ORDER BY ( SELECT NULL)) - 1 FROM E4
    )
SELECT 
    N,
    DATEADD(D, N, @BeginDate) AS TheDate
FROM Numbers
WHERE N <= DATEDIFF(D, @BeginDate, @EndDate)

答案 1 :(得分:1)

您可以使用WHILE循环执行此操作:

DECLARE @sdt DATE = '1989-01-01'
DECLARE @edt DATE = '2015-12-31'

WHILE @sdt <= @edt
BEGIN
    PRINT @sdt
    SET @sdt = DATEADD(dd, 1, @sdt )
END

或者使用递归CTE:

DECLARE @sdt DATE = '1989-01-01'
DECLARE @edt DATE = '2015-12-31';

WITH    cte
            AS ( SELECT   @sdt AS sdt
                UNION ALL
                SELECT   DATEADD(dd, 1, sdt)
                FROM     cte
                WHERE    DATEADD(dd, 1, sdt) <= @edt
                )
    SELECT  *
    FROM    cte
OPTION  ( MAXRECURSION 10000 )

@Bridge提供的链接中还有tally table方法

实际上答案是计数表。但如果没有很大的间隔,差异将是微不足道的。

答案 2 :(得分:0)

这样的事情应该适合你的目的:

DECLARE @sd date = '1989-01-01 00:00:00.000'
, @ed date = '2015-12-31 00:00:00.000'

DECLARE @tt TABLE(
    [Date] date
)


WHILE(@sd <= @ed) --Loop which checks each iteration if the date has reached the end
BEGIN
    INSERT INTO @tt
    SELECT @sd AS Date

    SET @sd = DATEADD(dd,1,@sd) --This willl increment the date so you actually advance the loop
END

SELECT * FROM @tt