在where子句+ SQL Server中IS NULL vs = NULL

Sre*_*har 18 sql t-sql sql-server

如何检查值IS NULL [or] = @param(@param为null)

例如:

Select column1 from Table1
where column2 IS NULL => works fine
Run Code Online (Sandbox Code Playgroud)

如果我想用@param替换比较值(IS NULL).如何才能做到这一点

Select column1 from Table1
where column2 = @param => this works fine until @param got some value in it and if is null never finds a record.
Run Code Online (Sandbox Code Playgroud)

这怎么能实现?

Lau*_*ves 37

select column1 from Table1
  where (@param is null and column2 is null)
     or (column2 = @param)
Run Code Online (Sandbox Code Playgroud)


Dan*_*Dan 6

我意识到这是一个古老的问题,但是我有一个相同的问题,并提出了另一个(简短的)答案。注意:这仅适用于支持ISNULL(expr,replacement)的MS SQL Server。

SELECT column1 FROM table1
WHERE ISNULL(column2,'') = ISNULL(@param,'')
Run Code Online (Sandbox Code Playgroud)

这还假定您以相同的方式对待NULL和空字符串。