I have a variable table:
DECLARE @A_Table TABLE(ID INT, att1 VARCHAR(100), att2 nvarchar(200))
I want to make dynamic sql, so I insert into this table some data (all inside a loop):
WHILE (@i <= 100) BEGIN
SELECT @other_att = NAME FROM @other_Table where ID = @i;
SET @sql = 'INSERT ' + @A_Table+ '(ID,att1,att2) SELECT '+CAST(@i AS VARCHAR)+' , '''+ @other_att+''', SUM('+ @other_att') FROM '+ @EVEN_OTHER_Table;
EXEC (@sql);
END
sql every time would look like:
INSERT INTO @A_Table SELECT 1 , 'subject', SUM(subject)
INSERT INTO @A_Table SELECT 2 , 'age', SUM(age)
INSERT INTO @A_Table SELECT 3 , 'sex', SUM(sex)....
AND after executing this : SO I will get:
@A_Table:
id att1 att2
1 subject 4.3
2 age 4.5
3 sex 4.1
but I get an error:
Msg 137, Level 16, State 1, Line 48
Must declare the scalar variable "@A_Table".
SO what is it the syntax to insert dynamically into a variable table?
Ok I have understood it.