我有一个这样声明的字符串变量:
declare @myGeniuses as nvarchar(8000);
set @myGeniuses = ' in (1,2,3)';
我想在 select 语句中应用我的变量,如下所示:
select * from GENIUSES where GeniusId @myGeniuses
我有一个这样声明的字符串变量:
declare @myGeniuses as nvarchar(8000);
set @myGeniuses = ' in (1,2,3)';
我想在 select 语句中应用我的变量,如下所示:
select * from GENIUSES where GeniusId @myGeniuses
declare @t nvarchar(max)
set @t='select * from GENIUSES where GeniusId'+ @myGeniuses
exec @t
你会做...
exec ('select * from GENIUSES where GeniusId' + @myGeniuses)
您将需要使用 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;