在我的数据库中,我打算将 - [TableName]作为第一列,将该表的所有列放在“,”(逗号后跟空格 - 分隔符)作为第二列 - 对于DB中的所有表
Table A | ColumnA1, ColumnA2, ColumnA3
Table B | ColumnB1, ColumnB2, ColumnB3
......................................
并将其作为XML检索
<TableList>
<TableName>TableA</TableName> <Columns> ColumnA1, ColumnA2, ColumnA3</Columns>
<TableName>TableB</TableName> <Columns> ColumnB1, ColumnB2, ColumnB3</Columns>
</TableList>
如何编写SQL查询?
答案 0 :(得分:4)
这将为您提供所要求的XML。
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')
但我认为这会返回一个更容易处理的XML。
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')
或者也许是这样。
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')
答案 1 :(得分:1)
你可以试试这个
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