Monday, March 28, 2011

Notes to self on XML PATH and String concatenation in t-sql for SQL2005, 2008 and beyond

Here's the query to be able to select the table name and get a concatenated list of the fields back. Very useful for generating queries on the fly.

SELECT
 t.table_name,
 STUFF((SELECT
             ', ' + column_name
FROM INFORMATION_SCHEMA.COLUMNS c where c.table_name = t.table_name
FOR XML PATH('')
), 1, 1, ''
) As concatenated_string
FROM INFORMATION_SCHEMA.TABLES t
WHERE table_name ='name_of_table'

I know it's not my usual type of post, but I keep forgetting the syntax and looking it up, so I put it where I 'll find it. :)

1 comment:

Unknown said...

That looks like something I'd write... bookmarked ;)