SQL从变量中选择条件IS NULL / IS NOT NULL

时间:2014-07-14 09:15:28

标签: sql-server select isnull

我正在尝试设计一个SELECT语句,它可以根据变量选择列为NULL或NOT NULL的行。

我希望这能更好地解释它:

DECLARE @var bit = 1;
IF (@var = 1)
  SELECT * FROM <table_name> WHERE <column_name> IS NULL
ELSE
  SELECT * FROM <table_name> WHERE <column_name> IS NOT NULL
GO

如果可能的话,我想将其简化为一个选择。

以下是伪代码:

SELECT * FROM <table_name> WHERE <column_name> IS @nullNotNullVar

有什么想法吗?

1 个答案:

答案 0 :(得分:0)

试试这个:

DECLARE @var bit = 1;

SELECT * 
FROM  <table_name> 
WHERE (@Var = 1 and <column_name> IS NULL)
  OR  (@Var = 0 and <column_name> IS NOT NULL)