Please start any new threads on our new site at https://forums.sqlteam.com. We've got lots of great SQL Server experts to answer whatever question you can come up with.

 All Forums
 SQL Server 2012 Forums
 Transact-SQL (2012)
 How to pivot this table

Author  Topic 

sql-lover
Yak Posting Veteran

99 Posts

Posted - 2014-09-30 : 14:22:45
If I have this query ...


SELECT names FROM PERSON

... which should give this set (not particular order)

John
Mary
Paul

how can I pivot the set so result will be something like this (including commas)

John, Mary, Paul

All on a single row or line.

James K
Master Smack Fu Yak Hacker

3873 Posts

Posted - 2014-09-30 : 15:32:45
You can make use of SQL XML to concatenate the rows with commas like this:
SELECT ','+names FROM PERSON FOR XML PATH('');
That has a one issue, which is that the output string has a comma at the beginning. To get rid of that comma, do this:
SELECT STUFF(
(SELECT ','+names FROM PERSON FOR XML PATH('')),
1,1,'');
Go to Top of Page

sql-lover
Yak Posting Veteran

99 Posts

Posted - 2014-09-30 : 15:40:10
quote:
Originally posted by James K

You can make use of SQL XML to concatenate the rows with commas like this:
SELECT ','+names FROM PERSON FOR XML PATH('');
That has a one issue, which is that the output string has a comma at the beginning. To get rid of that comma, do this:
SELECT STUFF(
(SELECT ','+names FROM PERSON FOR XML PATH('')),
1,1,'');




Interesting approach and thanks for reply. However, the result will feed a parameter for another query, which will run backup for databases.

Not sure if the XML will allow this.

Is there any T-SQL alternative to this?
Go to Top of Page

gbritton
Master Smack Fu Yak Hacker

2780 Posts

Posted - 2014-09-30 : 18:11:42
Post the other query
Go to Top of Page
   

- Advertisement -