Dynamic insert into variable table statement SQL Server -


i have variable table:

declare @a_table table(id int, att1 varchar(100), att2 nvarchar(200)) 

i want make dynamic sql, insert table data (all inside loop):

while (@i <= 100) begin            select @other_att  = name  @other_table id =  @i;   set @sql = 'insert ' + @a_table+ '(id,att1,att2) select '+cast(@i varchar)+' , '''+ @other_att+''', sum('+ @other_att') '+ @even_other_table; exec (@sql);  end  

sql every time like:

insert @a_table select 1 , 'subject', sum(subject) insert @a_table select 2 , 'age', sum(age) insert @a_table select 3 , 'sex', sum(sex)....  

and after executing : get:

@a_table: id    att1   att2 1   subject   4.3 2   age       4.5 3   sex       4.1 

but error:

msg 137, level 16, state 1, line 48 must declare scalar variable "@a_table". 

so syntax insert dynamically variable table?

ok have understood it.

you have table variable, not variable contains table name.

so need following.

while (@i <= 100) begin            select @other_att  = name  @other_table id =  @i;   set @sql = 'insert @a_table (id,att1,att2) select '+cast(@i varchar)+' , '''+ @other_att+''', sum('+ @other_att') @even_other_table'; exec (@sql);  end  

you need declare table variable statement inside @sql variable, , execute declare table , inserts together, or use local/global temporary table.

with local temporary table (stored in tempdb) this.

create table #testtbl (id int); exec ('insert #testtbl values (1)'); select * #testtbl drop table #testtbl 

some info temporary tables in bol

http://msdn.microsoft.com/en-us/library/ms174979.aspx - quite far down page

and table type.

http://msdn.microsoft.com/en-us/library/ms175010.aspx


Comments

Popular posts from this blog

c# - How to set Z index when using WPF DrawingContext? -

razor - Is this a bug in WebMatrix PageData? -

visual c++ - Using relative values in array sorting ( asm ) -