在T-SQL语句中删除while循环

时间:2015-12-24 07:27:55

标签: sql sql-server-2008 tsql while-loop temp-tables

在一个过程中有一些while循环,我想删除它们/替换为临时表或任何其他(不是游标)。

下面我创建了一个虚拟语法,我必须根据一些计算填充TEMP_TABLE表。请分享任何更好的选择:

SET @J = 0
SET @DIFFERENCE = 10
SET @INCREMENT = 2

WHILE (@J < @DIFFERENCE) 
BEGIN   
    SET @TO_DATE = (SELECT DATEADD(D, @INCREMENT, @TO_DATE))   

    IF (@TO_DATE <= GETDATE())
       INSERT INTO TEMP_TABLE 
       VALUES(@J, @TO_DATE)   

    SET @J = @J + @INCREMENT  
END

1 个答案:

答案 0 :(得分:1)

以下是使用Tally table

的一种方法
;WITH e1(n) AS
(
    SELECT 1 UNION ALL SELECT 1 UNION ALL SELECT 1 UNION ALL 
    SELECT 1 UNION ALL SELECT 1 UNION ALL SELECT 1 UNION ALL 
    SELECT 1 UNION ALL SELECT 1 UNION ALL SELECT 1 UNION ALL SELECT 1
), -- 10
e2(n) AS (SELECT 1 FROM e1 CROSS JOIN e1 AS b), -- 10*10
e3(n) AS (SELECT 2 FROM e1 CROSS JOIN e2), -- 10*100
e4(n)  as ( SELECT n = ROW_NUMBER() OVER (ORDER BY n) FROM e3)
SELECT n,
       Dateadd(D, n, @TO_DATE)
FROM   e4
WHERE  N <= @DIFFERENCE
       AND N%@INCREMENT = 0 

有关Generate a set or sequence without loops

的更多信息