SQL Server String Concatenation with Null

后端 未结 10 686
隐瞒了意图╮
隐瞒了意图╮ 2020-11-27 13:51

I am creating a computed column across fields of which some are potentially null.

The problem is that if any of those fields is null, the entire computed column will

相关标签:
10条回答
  • 2020-11-27 14:49

    You can also use CASE - my code below checks for both null values and empty strings, and adds a seperator only if there is a value to follow:

    SELECT OrganisationName, 
    'Address' = 
    CASE WHEN Addr1 IS NULL OR Addr1 = '' THEN '' ELSE Addr1 END + 
    CASE WHEN Addr2 IS NULL OR Addr2 = '' THEN '' ELSE ', ' + Addr2 END + 
    CASE WHEN Addr3 IS NULL OR Addr3 = '' THEN '' ELSE ', ' + Addr3 END + 
    CASE WHEN County IS NULL OR County = '' THEN '' ELSE ', ' + County END 
    FROM Organisations 
    
    0 讨论(0)
  • 2020-11-27 14:50

    Use

    SET CONCAT_NULL_YIELDS_NULL  OFF 
    

    and concatenation of null values to a string will not result in null.

    Please note that this is a deprecated option, avoid using. See the documentation for more details.

    0 讨论(0)
  • 2020-11-27 14:51

    You can use ISNULL(....)

    SET @Concatenated = ISNULL(@Column1, '') + ISNULL(@Column2, '')
    

    If the value of the column/expression is indeed NULL, then the second value specified (here: empty string) will be used instead.

    0 讨论(0)
  • 2020-11-27 14:55

    I had a lot of trouble with this too. Couldn't get it working using the case examples above, but this does the job for me:

    Replace(rtrim(ltrim(ISNULL(Flat_no, '') + 
    ' ' + ISNULL(House_no, '') + 
    ' ' + ISNULL(Street, '') + 
    ' ' + ISNULL(Town, '') + 
    ' ' + ISNULL(City, ''))),'  ',' ')
    

    Replace corrects the double spaces caused by concatenating single spaces with nothing between them. r/ltrim gets rid of any spaces at the ends.

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