How to concatenate columns properly using T-SQL?

前端 未结 6 1960
时光说笑
时光说笑 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:39

    This is an old question and SQL 2012 added the CONCAT function that made this sort of thing a bit easier. Try this:

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

    CONCAT will automatically treat NULL as empty string so you dont need to use ISNULL or COALESCE. The STUFF function is there to remove the first comma, as in the answer by Thomas

提交回复
热议问题