动态WHERE条件为空或非空

时间:2014-03-20 09:13:32

标签: tsql

我有一个存储过程,它以@flag为参数。该标志假设指示选择空值或无空值。

对于无null值我的解决方案看起来像:

@Flag int
SET @Flag = NULL

WHERE   ISNULL(column1,'') = ISNULL(@Flag,'')

有没有办法以类似的方式容纳无空值?如果没有什么是最紧凑的解决方案?

2 个答案:

答案 0 :(得分:1)

Flag int
SET @Flag = NULL

select * from table
WHERE (@flag is null and column is null) or ((@flag is not null and column is not null) and @flag = column)

我建议永远不要设置ANSI_NULL!这可能会导致许多不必要的维护痛苦。

无需像

那样的紧凑型解决方案
ISNULL(column1,'') = ISNULL(@Flag,'')

当@flag =''时,ill会返回null行,当flag为null时,还会返回''行

答案 1 :(得分:0)

我能想到的唯一方法是SET ANSI_NULL OFF然后进行比较:column1 = @flag