I'm trying to populate a temporary table to query later in a stored procedure. Because I'm populating the data from several tables I'm trying to do it in a loop using an EXEC statement:
Initially I got an error from my dynamic sql that I must declare the table variable. I do that but the sql outside my dynamic sql doesn't see the data in my temp table. Here's what my SQL looks like:
--Original Query:
DECLARE @sql2 varchar(8000)
set @sql2 = 'INSERT INTO @temp_table SELECT TOP 10 my_id, my_text FROM my_dynamic_table'
exec(@sql2)
select * from @temp_table --Normal query
Must declare the table variable "@temp_table" on the set @sql2 = 'INSERT... line
DECLARE @sql2 varchar(8000)
DECLARE @temp_table TABLE(my_id bigint NULL, my_text text NULL)
set @sql2 = 'DECLARE @temp_table TABLE(my_id bigint NULL, my_text text NULL);INSERT INTO @temp_table SELECT TOP 10 my_id, my_text FROM my_dynamic_table;select * from @temp_table;'
exec(@sql2)
select * from @temp_table --Normal query
I see the data when I run exec(@sql2), don't see it in the normal query.