sql server 3a concatinate column value without trailing or leading comma

Solutions on MaxInterview for sql server 3a concatinate column value without trailing or leading comma by the best coders in the world

showing results for - "sql server 3a concatinate column value without trailing or leading comma"
Margot
08 Aug 2020
1DECLARE @x TABLE(Id INT, City VARCHAR(32), Province VARCHAR(32), Country VARCHAR(32));
2
3INSERT @x(Id, City, Province, Country) VALUES
4(1,'Vancouver','British Columbia','Canada'),
5(2,'New York' , null             , null   ),
6(3, null      ,'Adama'           , null   ),
7(4, null      , null             ,'France'),
8(5,'Winnepeg' ,'Manitoba'        , null   ),
9(6, null      ,'Quebec'          ,'Canada'),
10(7,'Seattle'  , null             ,'USA'   );
11
12SELECT Id, Location = STUFF(
13      COALESCE(', ' + RTRIM(City),     '') 
14    + COALESCE(', ' + RTRIM(Province), '') 
15    + COALESCE(', ' + RTRIM(Country),  '')
16    , 1, 2, '')
17  FROM @x;