0

I have a table called contacts and i want to select all the distinct contact names (int) in one line separated by comma.

Currently i am using:

SELECT DISTINCT name FROM contacts

To get this result:

11111
22222
33333

But i need to have this result:

11111, 22222, 33333

I saw some examples with XML PATH but i couldn't adapt it to my code. Can anybody help me with the query please?

paulalexandru
  • 9,218
  • 7
  • 66
  • 94
  • this might be what you are looking for? http://blog.sqlauthority.com/2008/06/04/sql-server-create-a-comma-delimited-list-using-select-clause-from-table-column/ – trainoasis Jun 11 '14 at 09:54

4 Answers4

2

STUFF + XML PATH will do the job:

SELECT STUFF(
             (SELECT Distinct ',' + cast (name as varchar(20)) 
              FROM contacts       
              FOR XML PATH (''))
             , 1, 1, '')

demo:http://sqlfiddle.com/#!3/748e4/1

Milen
  • 8,697
  • 7
  • 43
  • 57
0

You can use STUFF:

SELECT 
    STUFF((
      SELECT distinct ',' + c.contacts
      FROM dbo.contacts c
      FOR XML PATH('')), 1, 1, '') as names; 
Ivan Cachicatari
  • 4,212
  • 2
  • 21
  • 41
0
       declare @t table  (Name Varchar(50))

       Insert into @t (Name) values ('1111'), ('2222'), ('3333')

        DECLARE @tt VARCHAR(MAX) 
        SELECT @tt= COALESCE(@tt + ', ', '') + Name from @t 
        SELECT @tt AS Result

OR 

   declare @t table  (Name Varchar(50))

   Insert into @t (Name) values ('1111'), ('2222'), ('3333')

SELECT SUBSTRING(
(SELECT ',' + s.Name
FROM @t s
ORDER BY s.Name
FOR XML PATH('')),2,200000) As Names
GO 
mohan111
  • 8,633
  • 4
  • 28
  • 55
0

Try this:

declare @contacts table(name nvarchar(100))

INSERT INTO @contacts (name) VALUES
('John'),
('Andrew'),
('Paul')

DECLARE @Result AS NVARCHAR(1000) -- Or even MAX if you need

SELECT @Result = ISNULL(@Result + ', ', '') + C.name
FROM (SELECT DISTINCT name FROM @contacts) C

SELECT @Result -- This is your actual result

The only thing you need to watch for is that the DISTINCT may affect the order of the names. That may or may not matter to you.

Mike Goatly
  • 7,380
  • 2
  • 32
  • 33