T-SQL: select rows not equal to a value, including nulls

前端 未结 5 521
闹比i
闹比i 2021-01-17 07:25

How do I select rows which don\'t equal a value and also include nulls in the returned data? I\'ve tried:

SET ANSI_NULLS OFF
SELECT TOP 30 FROM Mails
WHERE a         


        
5条回答
  •  无人及你
    2021-01-17 08:29

    When you have a lot of conditions, typing everything twice stinks. Here are two better alternatives:

    SELECT TOP 30 FROM Mails
    WHERE COALESCE(assignedByTeam,'') <> 'team01'
    

    The COALESCE operator returns the first non-null value in the list. If assignedByTeam is NOT null, it will compare the assignedByTeam value to 'team01'. But if assignedByTeam IS null, it will compare a blank '' to 'team01'. It's basically shorthand for the following:

    SELECT TOP 30 FROM Mails
    WHERE (CASE WHEN assignedByTeam IS NULL THEN '' ELSE assignedByTeam END) <> 'team01'
    

    The second way is to make your condition conditional, for example:

    SELECT TOP 30 FROM Mails
    WHERE 1 = CASE WHEN assignedByTeam = 'team01' THEN 0 ELSE 1 END
    

    In this example, the ELSE value will include all null rows, since they aren't equal to 'team01'.

提交回复
热议问题