In my database, I intend to get the - [TableName] as the first column and all columns of that table in a ", " (comma followed by space - delimiter) as the second column - for all tables in the DB.
Table A | ColumnA1, ColumnA2, ColumnA3
Table B | ColumnB1, ColumnB2, ColumnB3
......................................
And retrieve it as an XML
<TableList>
<TableName>TableA</TableName> <Columns> ColumnA1, ColumnA2, ColumnA3</Columns>
<TableName>TableB</TableName> <Columns> ColumnB1, ColumnB2, ColumnB3</Columns>
</TableList>
How should the SQL Query be written?
This will give you the XML you ask for.
select T.name as TableName,
(
select ', '+C.name
from sys.columns as C
where C.object_id = T.object_id
order by C.column_id
for xml path(''), type
).value('substring((./text())[1], 3)', 'varchar(max)') as Columns
from sys.tables as T
order by T.name
for xml path(''), root('TableList')
But I think this would return an XML that is easier to handle.
select T.name as TableName,
(
select ', '+C.name
from sys.columns as C
where C.object_id = T.object_id
order by C.column_id
for xml path(''), type
).value('substring((./text())[1], 3)', 'varchar(max)') as Columns
from sys.tables as T
order by T.name
for xml path('Table'), root('TableList')
Or perhaps like this.
select T.name as TableName,
(
select C.name as ColumnName
from sys.columns as C
where C.object_id = T.object_id
order by C.column_id
for xml path(''), type
) as Columns
from sys.tables as T
order by T.name
for xml path('Table'), root('TableList')
you may try this
select isc.TABLE_NAME,stuff((
SELECT ',' + cast(column_name as varchar(20))
FROM INFORMATION_SCHEMA.COLUMNS where TABLE_NAME =isc.TABLE_NAME
group by TABLE_NAME,COLUMN_NAME
FOR XML PATH('')
),1,1,'') as column_name from INFORMATION_SCHEMA.COLUMNS isc
group by TABLE_NAME
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.