在一个过程中有一些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
答案 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
的更多信息