T-SQL CASE Clause: How to specify WHEN NULL

后端 未结 15 1908
心在旅途
心在旅途 2020-11-28 05:42

I wrote a T-SQL Statement similar like this (the original one looks different but I want to give an easy example here):

SELECT first_name + 
    CASE last_na         


        
相关标签:
15条回答
  • 2020-11-28 05:51

    When you get frustrated trying this:

    CASE WHEN last_name IS NULL THEN '' ELSE ' '+last_name END
    

    Try this one instead:

    CASE LEN(ISNULL(last_Name,''))
    WHEN 0 THEN '' 
    ELSE ' ' + last_name
    END AS newlastName
    

    LEN(ISNULL(last_Name,'')) measures the number of characters in that column, which will be zero whether it's empty, or NULL, therefore WHEN 0 THEN will evaluate to true and return the '' as expected.

    I hope this is a helpful alternative.

    I have included this test case for sql server 2008 and above:

    DECLARE @last_Name varchar(50) = NULL
    
    SELECT 
    CASE LEN(ISNULL(@last_Name,''))
    WHEN 0 THEN '' 
    ELSE 'A ' + @last_name
    END AS newlastName
    
    SET @last_Name = 'LastName'
    
    SELECT 
    CASE LEN(ISNULL(@last_Name,''))
    WHEN 0 THEN '' 
    ELSE 'A ' + @last_name
    END AS newlastName
    
    0 讨论(0)
  • 2020-11-28 05:53

    There are plenty of solutions but none covers why the original statement doesn't work.

    CASE last_name WHEN null THEN '' ELSE ' '+last_name
    

    After the when, there is a check for equality, which should be true or false.

    If one or both parts of a comparison is null, the result of the comparison will be UNKNOWN, which is treated like false in a case structure. See: https://www.xaprb.com/blog/2006/05/18/why-null-never-compares-false-to-anything-in-sql/

    To avoid this, Coalesce is the best way.

    0 讨论(0)
  • 2020-11-28 05:54
    CASE WHEN last_name IS NULL THEN '' ELSE ' '+last_name END
    
    0 讨论(0)
  • 2020-11-28 05:57

    try:

    SELECT first_name + ISNULL(' '+last_name, '') AS Name FROM dbo.person
    

    This adds the space to the last name, if it is null, the entire space+last name goes to NULL and you only get a first name, otherwise you get a firts+space+last name.

    this will work as long as the default setting for concatenation with null strings is set:

    SET CONCAT_NULL_YIELDS_NULL ON 
    

    this shouldn't be a concern since the OFF mode is going away in future versions of SQl Server

    0 讨论(0)
  • 2020-11-28 05:59

    I tried casting to a string and testing for a zero-length string and it worked.

    CASE 
       WHEN LEN(CAST(field_value AS VARCHAR(MAX))) = 0 THEN 
           DO THIS
    END AS field 
    
    0 讨论(0)
  • 2020-11-28 06:00

    The problem is that null is not considered equal to itself, hence the clause never matches.

    You need to check for null explicitly:

    SELECT CASE WHEN last_name is NULL THEN first_name ELSE first_name + ' ' + last_name
    
    0 讨论(0)
提交回复
热议问题