0

可以通过 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 项,这取决于另一个结果

4

2 回答 2

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 )
于 2013-10-30T16:38:54.310 回答
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
于 2013-10-30T19:16:19.593 回答