如何从字符串创建t-sql

时间:2012-05-23 19:41:18

标签: sql-server tsql sql-server-2000

我有一个声明如下的字符串变量:

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

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

select * from GENIUSES where GeniusId @myGeniuses

3 个答案:

答案 0 :(得分:1)

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

exec @t

答案 1 :(得分:1)

你会做的......

exec ('select * from GENIUSES where GeniusId' + @myGeniuses)

答案 2 :(得分: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;