How to concatenate columns properly using T-SQL?

前端 未结 6 1944
时光说笑
时光说笑 2020-12-05 14:11

I have a address in more than one column in a table.

SELECT FirstName, LastName, StreetAddress, City, Country, PostalCode 
FROM Client

I a

6条回答
  •  抹茶落季
    2020-12-05 14:57

    When you concatenate anything with a null, it returns null. So I'm trying to concatenate a comma with the given column value and if that expression returns null, I use Coalesce to return an empty string. At the end, if I get a value, the entire result will start with a comma. So I remove that comma using the Stuff function.

    Select Stuff(
        Coalesce(',' + FirstName,'')
        + Coalesce(',' + LastName,'')
        + Coalesce(',' + StreetAddress,'')
        + Coalesce(',' + City,'')
        + Coalesce(',' + Country,'')
        + Coalesce(',' + PostalCode ,'')
        , 1, 1, '')
    From Client
    

    If you only want the address, then obviously you would only include those columns:

    Select FirstName, LastName
        , Stuff(
            Coalesce(',' + StreetAddress,'')
            + Coalesce(',' + City,'')
            + Coalesce(',' + Country,'')
            + Coalesce(',' + PostalCode ,'')
        , 1, 1, '')
    From Client
    

提交回复
热议问题