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

前端 未结 5 462
闹比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:15
    SELECT TOP 30 FROM Mails
    WHERE ISNULL(AssignedByTeam,'') <> 'team01'
    

    I saw a coalesce statement version but ISNULL() is more efficient.

    0 讨论(0)
  • 2021-01-17 08:15
     where column != 'value' or column is null
    
    0 讨论(0)
  • 2021-01-17 08:16
    SELECT TOP 30 FROM Mails
    WHERE assignedByTeam <> 'team01'
    OR assignedByTeam is null
    
    0 讨论(0)
  • 2021-01-17 08:21

    Try checking for NULL explicitly:

    SELECT TOP 30 col1, col2, ..., coln
    FROM Mails
    WHERE (assignedByTeam <> 'team01' OR assignedByTeam IS NULL)
    
    0 讨论(0)
  • 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'.

    0 讨论(0)
提交回复
热议问题