T-SQL - Using AND condition only if a value from a list is present

笑着哭i 提交于 2019-12-02 08:18:39

This looks odd at first read, but it works. I have this in a search SP to take into consideration only parameters with a non-NULL value. When the parameter is non-NULL, it is comma-separated string coming from the app.

WHERE ..................
AND (MyTable.MyColumn IN (SELECT * FROM dbo.func_SplitString(@Parameter, ',')) OR @Parameter IS NULL)

Note that dbo.func_SplitString returns a TABLE data type.

You can use nested cases:

(CASE WHEN Table1.field3 IN ( 1001, 1002, 1003, 1004, 1005, 1006, 1007) 
    THEN (CASE WHEN Table2.fieldvalue = importantvalue THEN 1 ELSE 0 END)
    ELSE 1
END ) = 1

You can even make it single condition, but beware of the way NOT IN deals with nulls:

(
    Table2.fieldvalue = importantvalue OR 
    Table1.field3 NOT IN ( 1001, 1002, 1003, 1004, 1005, 1006, 1007) OR
    Table1.field3 IS NULL
) 
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!