Using CASE in WHERE Statement when parameter has multiple values

半城伤御伤魂 提交于 2019-12-02 06:15:13

If your @ServiceActivity is something like 1,2,3

You can do something like this

WHERE  `,1,2,3,` LIKE `%,1,%` 

So you format your variables

WHERE  ',' + @ServiceActivity + ',' LIKE '%,' + ID + ',%'

SQL FIDDLE DEMO

SELECT *
FROM 
    (SELECT '1,2,3,4' as X UNION ALL
     SELECT '2,3,4,5' as X UNION ALL
     SELECT '3,4,5,6' as X UNION ALL
     SELECT '1,3,4,5' as X 
     ) as T
WHERE ',' + X + ','  LIKE  '%,1,%'

For Your Case

(CASE WHEN @YESNOActivity = 'Yes' 
           THEN ',' + @ServiceActivity + ','
           ELSE NULL 
 END)
LIKE
(CASE WHEN @YESNOActivity = 'Yes' 
           THEN '%,' + TblActivity.ActivityServActId + ',%'
           ELSE 0 
 END) 
Philip Kelley

In SQL, the IN clause does not support parameters the way you are using them. The general syntax is

IN (1, 2, 3, 4)

you have

IN (@Param)

where something like @Param = '1, 2, 3, 4'

Internally, SQL will turn this into

IN ('1, 2, 3, 4')

Note the quotes... you are now matching against a string!

There are a number of ways to address this. Search SO for "sql in clause parameter", pick one that works for you, and upvote it.


(Added)

Parameterize an SQL IN clause seems pretty definitive on the subject. While long ago I upvoted the third reply (the one with table-value parameters), any of the high-vote answers could do the trick. The ideal answer depends on the overall problem you are working with. (I am not familiar with SSRS, and can't give more specific advice.)

So after a lot of messing around I put together a simple workaround for this by dropping my use of CASE altogether - but I have a suspicion that this is not a terribly efficient way of doing things.

WHERE
(@YESNOActivity = 'No' OR (@YESNOActivity = 'Yes' AND
TblActivity.ActivityServActId IN (@ServiceActivity)))

AND

(@YESNOContract = 'No' OR (@YESNOContract = 'Yes' AND
TblActivity.ActivityContractId IN (@Contract)))
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!