0

我正在尝试迭代地设置表变量的各个列,如下所示:

declare @reg_data table
(
    I int NOT NULL PRIMARY KEY IDENTITY,
    Y float
)

declare @counter int, @numRows int
SET @counter = 0
SET @numRows = (select MAX(val) + 10 from tableY)

WHILE @counter < numRows
BEGIN
    SET @reg_data.Y = dbo.func1(@counter)       --HOW DO I DO THIS!!!  
    @counter = @counter + 1
END

以上不起作用,因为您无法访问像数组这样的表变量。如何获得以下功能?

4

3 回答 3

1

您不能在不存在的记录中设置值,因此您需要一个insert

WHILE @counter < numRows
BEGIN
    INSERT INTO @reg_data (Y) values (dbo.func1(@counter))
    @counter = @counter + 1
END
于 2012-08-11T16:07:43.130 回答
1

为了完整起见,一个带有 CTE 且没有循环的单语句示例:

DECLARE @reg_data TABLE (
    I INT NOT NULL PRIMARY KEY IDENTITY,
    Y FLOAT
);

WITH cteNum AS (
    SELECT MAX(val) + 10 AS val
    FROM @tableY
    HAVING MAX(val) >= 0
    UNION ALL
    SELECT val-1
    FROM cteNum
    WHERE val > 0
)
INSERT @reg_data(Y)
    SELECT dbo.func1(val)
    FROM cteNum
    OPTION (MAXRECURSION 0);
于 2012-08-11T20:45:04.227 回答
0

为什么要为此使用光标?

你为什么不写一些UPDATE语句:

WHILE @counter < numRows
BEGIN
    UPDATE @reg_data
    SET Y = dbo.func1(@counter)  
    WHERE I = @counter

    SET @counter = @counter + 1
END

您需要能够以某种方式从table变量中读取标识值(IUPDATEI

于 2012-08-11T16:02:10.297 回答