Table variable and exec

10,251

Solution 1

The table @FileIDs is not in the scope of exec(@testquery).

That's why you have that problem.


To solve this problem you may use a temporary table:

CREATE table #FileIDs
(
   File_ID int
)
insert into #FileIDs select ID from Files where Name like '%bla%'; 

DECLARE @testquery as varchar(max);
set @testquery = 'select * from #FileIDs';
exec(@testquery);

drop table #FileIDs

or put the table in the scope:

DECLARE @sql nvarchar(2000)

SET @sql='DECLARE @FileIDs TABLE (   File_ID int);'
SET @sql=@sql+'insert into @FileIDs select ID from Files where Name like ''%bla%'';'
set @sql=@sql+ 'select * from @FileIDs;'
EXECUTE sp_executesql @sql

Solution 2

Indeed table is out of the scope, try this:

DECLARE @sql nvarchar(2000)

SET @sql='DECLARE @FileIDs TABLE (   File_ID int);'
SET @sql=@sql+'insert into @FileIDs select ID from Files where Name like ''%bla%'';'
set @sql=@sql+ 'select * from @FileIDs;'
EXECUTE sp_executesql @sql

Solution 3

 CREATE table #FileIDs
(
   File_ID int
)
insert into #FileIDs select ID from Files where Name like '%bla%'; 

DECLARE @testquery as varchar(max);
set @testquery = 'select * from #FileIDs';
exec(@testquery);

drop table #FileIDs
Share:
10,251
alex555
Author by

alex555

Updated on June 04, 2022

Comments

  • alex555
    alex555 about 2 years

    How can I use a table variable while executing a command string?

    DECLARE @FileIDs TABLE 
    (
       File_ID int
    )
    insert into @FileIDs select ID from Files where Name like '%bla%';
    
    DECLARE @testquery as varchar(max);
    set @testquery = 'select * from @FileIDs';
    exec(@testquery);
    

    returns the following error

    Msg 1087, Level 15, State 2, Line 1 Must declare the table variable "@FileIDs".