0

我有一个这样声明的字符串变量:

declare @myGeniuses as nvarchar(8000);
set @myGeniuses = ' in (1,2,3)';

我想在 select 语句中应用我的变量,如下所示:

select * from GENIUSES where GeniusId @myGeniuses
4

3 回答 3

1
declare @t nvarchar(max)
set @t='select * from GENIUSES where GeniusId'+ @myGeniuses

exec @t
于 2012-05-23T19:43:35.667 回答
1

你会做...

exec ('select * from GENIUSES where GeniusId' + @myGeniuses)
于 2012-05-23T19:44:25.493 回答
1

您将需要使用 sp_executesql 来实现该结果,这使您可以将查询语句作为字符串传递并执行它。

有关更多详细信息,请参见:http: //msdn.microsoft.com/en-us/library/ms188001.aspx

示例用法:

DECLARE @sql AS NVARCHAR(MAX); 
DECLARE @filter AS NVARCHAR(500); 
SET @filter = ' in (1,2,3)'; 
SET @sql = 'select * from GENIUSES where GeniusId' + @filter; 
EXECUTE sp_executesql @sql; 
于 2012-05-23T19:44:51.800 回答