TSQL set the column value of a table variable
-
25-06-2021 - |
Question
I am trying to set individual columns of a table variable iteratively as follows:
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
The above does not work because you cannot access table variables like an array. How can I obtain the following functionality?
Solution
You can't set values in records that doesn't exists, so you need an insert
:
WHILE @counter < numRows
BEGIN
INSERT INTO @reg_data (Y) values (dbo.func1(@counter))
@counter = @counter + 1
END
OTHER TIPS
Just for the completeness a one-statement example with a CTE and no looping:
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);
Why use a cursor for this at all??
Why don't you just write some UPDATE
statements:
WHILE @counter < numRows
BEGIN
UPDATE @reg_data
SET Y = dbo.func1(@counter)
WHERE I = @counter
SET @counter = @counter + 1
END
You need to somehow be able to read out the identifying values (the I
) from the table variable, so you can use that in your UPDATE
statement to apply the update to exactly one row (that's identified by that value of I
)
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow