Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

t-sql Table columns to String

Is it possible to string a table columns headers dynamically from information_schema recursively

So if I had 2 tables (or however many) in my database with 5 columns each

Could I get the query to find this tables by schema and then string all the table columns hearders into another table ending up with something like

table name ¦ string 
Table A    ¦ id,columnName1,columnName2 ,columnName3 ,columnName4 ,columnName5
Table b    ¦ id,columnName1,columnName2 ,columnName3 ,columnName4 ,columnName5

(THESE ARE TWO ROWS BTW)

like image 835
user2181700 Avatar asked Apr 26 '26 02:04

user2181700


2 Answers

It can be simpler, no XML:

declare @columns varchar(1000)
set @columns=''

select @columns = @columns + ',' + name
from sys.columns 
where object_id = object_id('MyTable')
like image 61
Alex from Jitbit Avatar answered Apr 30 '26 08:04

Alex from Jitbit


Something using FOR XML PATH('') in combination with the sys.columns and sys.tables could work:

SELECT t.name [TableName], 
(
    SELECT name + ','
    FROM sys.columns c
    WHERE c.object_id = t.object_id
    FOR XML PATH('')
) [String]
FROM sys.tables t

It basically takes the columns returned from a query and formats is as XML, where the element tags are defined in the PATH(''). If you leave it blank, though, it will omit the tags and return a string instead.

The documentation on MSDN also has a lot of different examples with other uses for the FOR XML clause.

like image 26
valverij Avatar answered Apr 30 '26 08:04

valverij



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!