1

在我的数据库中,我打算将 - [TableName] 作为第一列,并将“,”(逗号后跟空格 - 分隔符)中该表的所有列作为第二列 - 对于数据库中的所有表。

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 Query应该怎么写?

4

2 回答 2

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')
于 2012-10-20T07:00:06.970 回答
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
于 2012-10-20T06:56:30.367 回答