WHERE子句的条件

时间:2016-05-20 10:39:34

标签: sql sql-server

我的脚本有一个并不总是包含值的变量。如果有值,我需要一个额外的WHERE子句。

DECLARE @identityUserIds NVARCHAR;
SELECT @identityUserIds = (SELECT TOP (1) [userIdsCsv] FROM [identityUsers])

SELECT *
FROM [Users]
-- IF (!ISNULL(@identityUserIds) OR @identityUserIds != '')
WHERE [ID] in (@identityUserIds)
-- ELSE (no extra condition)

我该怎么做?

3 个答案:

答案 0 :(得分:1)

执行此操作的常用方法是:

 ... where @identityUserIds is null or ID in (@identityUserIds)

答案 1 :(得分:0)

我认为这可以通过RecyclerView

完成
OR

但请注意@ Rhumborl的评论是正确的,SELECT * FROM [Users] WHERE Len(ISNULL(@identityUserIds,''))=0 OR [ID] IN (@identityUserIds) 语句不适用于字符串。不幸的是,我没有那个问题的直接解决方案。

答案 2 :(得分:0)

...其中ID为(ISNULL(@ identityUserIds,ID))