表变量和exec

时间:2012-07-06 10:20:01

标签: tsql exec local-variables

如何在执行命令字符串时使用表变量?

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);

返回以下错误

Msg 1087,Level 15,State 2,Line 1 必须声明表变量“@FileIDs”。

3 个答案:

答案 0 :(得分:3)

表格@FileIDs不在exec(@testquery)范围内。

这就是你遇到这个问题的原因。


要解决此问题,您可以使用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

将表格放在范围内:

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

答案 1 :(得分:3)

确实表不在范围内,试试这个:

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 :(得分:2)

 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