Extracting Column Names for a Table in SQL as a CSV String
I had a need (creating CSV BCP files) that required knowing the column names of a MS SQL table in the order they were created. Some inspiration from Mark Clerget and a little fooling around with SQL Query Analyzer resulted in the following.
DECLARE @c varchar(4000), @t varchar(128)
SET @c = ''
SET @t='authors'
SELECT @c = @c + c.name + ', '
FROM syscolumns c INNER JOIN sysobjects o ON o.id = c.id
WHERE o.name = @t
ORDER BY colid
SELECT Substring(@c, 1, Datalength(@c) - 2)
Which gives the following result:
au_id, au_lname, au_fname, phone, address, city, state, zip, contract
Perfect. Note the use of @c = @c + c.name in the select clause to colapse 9 rows into 1 row. I've used this technique many times in the past to generate a single string from multiple rows without resorting to cursors.
Trackback address for this post
Trackback URL (right click and copy shortcut/link location)
7 comments
I didn't get the gig, but did write their manager an email stating that they're interview process was flawed and that my solution was 1000 times faster than theirs.
Yeah, I was a little punk.
The saying...."In the land of the blind, the one-eyed man is King" applies to your experience. So maybe a little rewording..."In the land SQL wannabe interviewer, the CURSOR approach is King!". Anyway, you inspired me to share a similar experience that I think many of us have encountered about the root causes of project success and failure. I'll be blogging it soon. Thanks!
use pubs
DECLARE @c varchar(4000), @t sysname
SET @c = ''
SET @t='authors'
SELECT @c = @c + C.COLUMN_NAME + ', '
FROM INFORMATION_SCHEMA.COLUMNS C
WHERE c.TABLE_NAME = @t
ORDER BY ORDINAL_POSITION
SELECT Substring(@c, 1, Datalength(@c) - 2)
Vern
mark
I found this very useful for my code.
This post has 2 feedbacks awaiting moderation...



