在 SQL Server 2012 的循环插入中递增变量

Incrementing a variable inside a looped INSERT in SQL Server 2012

我们如何才能包含其他列以与此代码中的循环月份相同进行循环?

我想要实现的是 $datestart 的范围,$dateend 也应该循环 [Data 3]

[Data 3]等于100,则$datestart$dateend的取值范围为10

数据 3 列应从 100,101,102,103,104,105.. 递增至 110

DECLARE @MYTESTTABLE TABLE  
                     (
                          [Month] DATE, 
                          [Data 1] INT, 
                          [Data 2] INT, 
                          [Data 3] INT
                     );

WITH MYLOOP AS 
(
    SELECT CAST('$datestart' AS DATE) AS [date], '$datavalue' AS [Data 3]
    UNION ALL
    SELECT DATEADD(MONTH, 1, [date]), [Data 3] = [Data 3] + 1
    FROM MYLOOP
    WHERE DATEADD(MONTH, 1, [date]) <  CAST('$dateend' AS DATE)
)
INSERT INTO @MYTESTTABLE ([Month], [Data 1], [Data 2], [Data 3])
    SELECT 
        LEFT([date], 10) AS [Month], 100 AS [Data 1], 100 AS [Data 2], [Data 3]
    FROM 
        MYLOOP

SELECT * 
FROM @MYTESTTABLE

假设$datavalue等于100,它会随着循环范围从$datestart$dateend.

循环

例子

下一列(数据 3)应该是 100,101,102,103,104,... 等等

我们怎样才能做到这一点?

我试过这样做 [Data 3] = [Data 3] + 1 但我得到这个错误:

Types don't match between the anchor and the recursive part in column "Data 3" of recursive query "MYLOOP".

错误消息恰好是 SQL 服务器选择的第一个错误。事实上,您的 SQL 有很大的错误 SQL 服务器没有报告。

首先T-SQL使用@variablename来表示变量(不是$variablename)。其次,用单引号 (') 括起某些内容将导致 SQL 服务器将其视为文字字符串。如果您在查询 window 中输入以下内容:

SELECT CAST('$datestart' as date)

您将收到转换失败错误消息。

此外,我强烈建议您强烈键入变量@datestart 和@dateend,这样您就不需要使用强制转换。

例如,尝试以下操作:

DECLARE @datestart date = '2019-01-01'
DECLARE @dateend date = '2019-11-02'
DECLARE @datavalue int = 100

DECLARE @MYTESTTABLE TABLE ([Month] date, [Data 1] INT, [Data 2] INT, [Data 3] INT);


;WITH MYLOOP AS (
    SELECT @datestart AS [date], @datavalue as [Data 3]
    UNION ALL
    SELECT DATEADD(MONTH, 1, [date]), [Data 3]=[Data 3]+1
    FROM MYLOOP
    WHERE DATEADD(MONTH, 1, [date]) <  @dateend) 

INSERT INTO @MYTESTTABLE ([Month], [Data 1], [Data 2], [Data 3])
SELECT [date] AS [Month], 100 AS [Data 1], 100 AS [Data 2], [Data 3]
FROM MYLOOP;

SELECT * FROM @MYTESTTABLE

这将为您提供从 2019-01-01 到 2019-11-01 的数据。请注意,我将 @dateend 设置为 2019-11-02,因为您使用的是 < @dateend。这确保您也将获得所需的最后日期。否则你可以使用 <=。