SQL – Convert rows of single column data to one row of columns

Transform a single column of data to a single row of data one column per each original row. I needed to quote-comma delimit the columns too.


SELECT name
FROM sys.sysdatabases
WHERE name LIKE '%master%'
ORDER BY name

SELECT TOP 1
 STUFF((
 SELECT ', "' + name + '"'
 FROM sys.sysdatabases
 WHERE name LIKE '%master%'
 ORDER BY name
 FOR
 XML PATH('')
 ), 1, 1, '')
FROM sys.sysdatabases

/*
name
--------------------------------------------
master
master_admin
master_settings
--------------------------------------------
 "master", "master_admin", "master_settings"
*/

Comments are closed.

Post Navigation