troubleshooting Question

Working with comma separated strings in a sql server table

Avatar of maqskywalker
maqskywalker asked on
Microsoft SQL ServerSQL
7 Comments1 Solution47 ViewsLast Modified:
Hi Experts,

I'm using the Employees table from the Northwind Traders sample database.

I'm only using these columns.


If I use this query

SELECT [name] AS ColNames 
FROM syscolumns 
WHERE id=OBJECT_ID('Employees')
AND [colid] < 4
ORDER BY [colid]

Open in new window

I get the column names


If I use the STRING_AGG function query, i get this string:

SELECT '(' + STRING_AGG([EmployeeID], ',') + '),' 
     + '(' + STRING_AGG([LastName], ',') + '),'
     + '(' + STRING_AGG([FirstName], ',') + ')' AS [StringCol]
FROM [Northwind].[dbo].[Employees]

Open in new window


What's an elegant way to get this result ?

I want to add the column name to the beginning of each part of the string like on this mockup image.

One way i was thinking, is before i even use the the STRING_AGG, in a select statement select all columns and add the column name to row 1 of each column,  
Then once I added the column name to row 1 of every column than i could use STRING_AGG. But not sure if that is a good approach.

Join our community to see this answer!
Unlock 1 Answer and 7 Comments.
Start Free Trial
Learn from the best

Network and collaborate with thousands of CTOs, CISOs, and IT Pros rooting for you and your success.

Andrew Hancock - VMware vExpert
See if this solution works for you by signing up for a 7 day free trial.
Unlock 1 Answer and 7 Comments.
Try for 7 days

”The time we save is the biggest benefit of E-E to our team. What could take multiple guys 2 hours or more each to find is accessed in around 15 minutes on Experts Exchange.

-Mike Kapnisakis, Warner Bros