使用SQL Server中的三元函数,基于bit确定|是否为NULL ?

时间:2022-02-05 10:24:50

Say I have an input parameter to a stored procedure @flag

假设我有一个存储过程@flag的输入参数

I want to filter my query based on some column col1 being null, based on the value of this flag.

我想根据col1的某个列为null,基于这个标志的值,过滤我的查询。

Say if @flag = 1, show only records with col1 IS NULL, if @flag = 0, show only records with col1 IS NOT NULL

如果@flag = 1,那么只显示col1的记录为空,如果@flag = 0,那么只显示col1的记录为非空

My intuition would lead me to this:

我的直觉告诉我:

select * 
from table1 
where col1 IS IIF(@flag = 1, NULL, NOT NULL);

This does compile. Is there any other concise way to do this?

这并编译。还有其他简洁的方法吗?

1 个解决方案

#1


4  

Even when your query compiles I doubt it will work. But you can do it with boolean and/or logic

即使您的查询编译成功,我也怀疑它是否有效。但是你可以用布尔和/或逻辑来做

select * from table1 
where (@flag = 1 and col1 IS NULL)
   or (@flag = 0 and col1 IS NOT NULL)

#1


4  

Even when your query compiles I doubt it will work. But you can do it with boolean and/or logic

即使您的查询编译成功,我也怀疑它是否有效。但是你可以用布尔和/或逻辑来做

select * from table1 
where (@flag = 1 and col1 IS NULL)
   or (@flag = 0 and col1 IS NOT NULL)