Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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,
like image 882
MattJ Avatar asked Oct 30 '14 04:10

MattJ


People also ask

How do I remove the last comma character from a string?

To remove the last comma from a string, call the replace() method with the following regular expression /,*$/ as the first parameter and an empty string as the second. The replace method will return a new string with the last comma removed.


2 Answers

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".

like image 129
Ben Thul Avatar answered Oct 02 '22 10:10

Ben Thul


This works for me->

1.Inserting comma Before Data

2.Using Stuff to Remove it

select (stuff((
   SELECT ', '+ Name  AS 'data()' 
   FROM Table_1 
   FOR XML PATH('')),
   Count('ID')
, 1, ' '))as Result
like image 37
Musab Avatar answered Oct 02 '22 11:10

Musab