问题
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".
回答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
回答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
回答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
来源:https://stackoverflow.com/questions/11360317/table-variable-and-exec