How do the SQL “IS” and “=” operators differ?

后端 未结 5 1976
粉色の甜心
粉色の甜心 2021-01-03 21:59

I am building some prepared statements that use parametrized values. As an example:

SELECT * FROM \"Foo\" WHERE \"Bar\"=@param

Sometimes

5条回答
  •  执念已碎
    2021-01-03 22:31

    You want records from Foo where Bar = @param, or if @param is null, where Bar is null. Some of the proposed solutions will give you null records with nonnull @param, which does not sound like your requirement.

    Select * from Foo where (@param is null and Bar is null) or (Bar = @param)
    

    This doesn't say whether this is Oracle or SQL Server or another RDBMS, because they each implement slightly different helper functions. SQL's ISNULL(first, second) like NVL(first, second). I like SQL Server's COALESCE() for the general applicability.

    The IS comparison is only for null comparisons.

    If you are using SQL Server and if you really need a different 3VL logic truth table to solve your problem (that is, if you have a specific need for "NULL=NULL" to be "true" at some point in time, and also recognize that this is deprecated and barring your reasons, not a good idea in general), within your code block you can use the directive

    SET ANSI_NULLS OFF

    Here's the BOL on it: http://msdn.microsoft.com/en-us/library/ms188048.aspx

提交回复
热议问题