WHERE子句中IN字符串的SQL Server存储过程参数

时间:2018-04-07 22:06:08

标签: sql-server

存储过程ItemList具有WHERE子句IN过滤器的字符串参数:

WHERE Item IN (@FilterStr)

如果过滤器仅为单个项目,则无效。

EXEC ItemList 'ABC'

如果需要为下面的SQL WHERE子句传递多个项,如何调用存储过程?

WHERE Item IN ('ABC', 'DEF', 'HJK')

无法通过'ABC','DEF','HJK'传递它。因为逗号将是参数分隔符。感谢。

2 个答案:

答案 0 :(得分:0)

假设该项目为VARCHAR。您可以尝试以下。

DECLARE @FilterStr VARCHAR(MAX)
SET @FilterStr ='''ABC'',''DEF'',''HJK'''

--Query
WHERE Item IN (
SELECT 
        Split.a.value('.', 'VARCHAR(100)') AS Item  
FROM  
    (
    SELECT CAST ('<M>' + REPLACE(@FilterStr, ',', '</M><M>') 
              + '</M>' AS XML) AS CVS 
    ) AS A CROSS APPLY CVS.nodes ('/M') AS Split(a)
)

答案 1 :(得分:0)

declare @parameters nvarchar(100) = '''AAA'',''BBB'',''CCC''';
declare @Query nvarchar(100) = 'select * from [WFL].[TBL_WFTBaseInfo] where 
[wbiEntity] in ('+@parameters+' )';
exec(@query)