SQL Server: how to remove last comma after combining rows using XML Path

MattJ picture MattJ · Oct 30, 2014 · Viewed 15k times · Source

I found a way to combine multiple row's into one row which is comma separated but now I would like to remove the last comma.

CREATE TABLE supportContacts 
(
   id int identity primary key, 
   type varchar(20), 
   details varchar(30)
);

INSERT INTO supportContacts (type, details)
VALUES ('Email', '[email protected]'),
       ('Twitter', '@sqlfiddle');

This query combines types, but I want to now remove the last comma:

SELECT top (2) 
    type + ', ' AS 'data()'
FROM  
    supportContacts
ORDER BY 
    type DESC
FOR XML PATH('')

This is the current result:

Twitter, Email,

Answer

Ben Thul picture Ben Thul · Oct 30, 2014

While you already have an answer, another common idiom that you'll see is:

select stuff((
    SELECT top (2) 
        ', ' type AS 'data()'
    FROM  
        supportContacts
    ORDER BY 
        type DESC
    FOR XML PATH('')
), 1, 2, '')

This says "take the result of the select and replace the two characters starting at position 1 with a zero-length string".