Where声明来自声明的变量Sql Server

时间:2013-10-30 16:10:36

标签: sql-server

可以在SQL Server 2008中通过声明的变量传递Where语句吗?我该怎么做?

declare @foo as nvarchar(max) = '9510,9580,5030'
SELECT T1.[ItemCode]
FROM tbl1 T1
WHERE T1.ItemCode in (@foo)

当我运行此代码时,我的foo变量可以包含至少一个项目或100个项目,这取决于另一个结果

2 个答案:

答案 0 :(得分:1)

您可以使用exec执行此操作。

declare @foo as nvarchar(max) = '9510,9580,5030'

declare @SQLString as nvarchar(max)
set @SQLString  = 'SELECT T1.[ItemCode]
                   FROM tbl1 T1
                   WHERE T1.ItemCode in (' + @foo + ')'
exec (@SQLString )

答案 1 :(得分:0)

我会使用表变量:

DECLARE @foo AS NVARCHAR(max) = 'yourstring'

DECLARE @SQLString table (name NVARCHAR(max))

    INSERT INTO @SQLString
    SELECT T1.[ItemCode]
    FROM tbl1 T1
    WHERE T1.ItemCode LIKE ('%' + @foo + '%')

SELECT * FROM @SQLString