我希望列出我的数据库中的每个表以及相应的列标题。 SQL是否有办法在此过程中按字母顺序排列列名?
格式化线上的东西:
Table1 Col1name Col2name Col3name ...
Table2 Col1name Col2name Col3name ...
...
谢谢!
答案 0 :(得分:5)
SELECT
[schema] = s.name,
[table] = t.name,
[column] = c.name
FROM
sys.tables AS t
INNER JOIN
sys.schemas AS s
ON t.[schema_id] = s.[schema_id]
INNER JOIN
sys.columns AS c
ON t.[object_id] = c.[object_id]
ORDER BY
t.name,
c.name;
这就是为什么我不会在SQL Server 2005 +中使用INFORMATION_SCHEMA
的原因:
答案 1 :(得分:1)
SQL Server有一个名为sp_MSforeachtable的无证件存储过程,您可以使用它来遍历数据库中的所有表
知道了表格名称后,您可以使用Information schema views或info schema view for Columns查看表格中的所有列
答案 2 :(得分:0)
这应该让你朝着正确的方向前进。真的取决于你想要的输出:
SELECT t.table_name, STUFF((SELECT distinct ',' + c.COLUMN_NAME
FROM DATABASENAME.INFORMATION_SCHEMA.COLUMNS c WHERE c.TABLE_NAME =t.table_name
FOR XML PATH(''), TYPE
).value('.', 'NVARCHAR(MAX)')
,1,1,'') as Columns
FROM DATABASENAME.INFORMATION_SCHEMA.TABLES t
ORDER BY t.TABLE_NAME, Columns
如果使用@Aaron指出的sys.tables和sys.columns,那么这也应该有效:
SELECT t.name, STUFF((SELECT distinct ', ' + c.name
FROM sys.COLUMNS c WHERE t.object_id = c.object_id
FOR XML PATH(''), TYPE
).value('.', 'NVARCHAR(MAX)')
,1,1,'') as Columns
FROM sys.TABLES t
ORDER BY t.name, Columns
祝你好运。
答案 3 :(得分:0)
试试这个
declare @xml as xml
declare @max_cols int
declare @i int
declare @query as varchar(max)
declare @query_OA2 as varchar(max)
select @max_cols = MAX(n)
from( select COUNT(name) as n
from sys.columns
group by object_id
)V
select @i = 1, @query_OA2 = ''
while @i <= @max_cols
begin
set @query_OA2 = @query_OA2 +', C.elements.value(''./name['+CAST(@i as varchar(max))+']'',''varchar(max)'') as [Column '+CAST(@i as varchar(max))+']'
set @i = @i+1
end
select @query_OA2 = STUFF(@query_OA2,1,1,'')
select @query = 'select t.name as [table]
,OA2.*
from sys.tables t
outer apply (select (select (select c.name from sys.columns c
where c.object_id = t.object_id
order by c.column_id
for xml path(''''),type) for xml path(''columns''),type) as cols
)OA
outer apply (select '+@query_OA2+'
from OA.cols.nodes(''columns'')C(elements)
)OA2
order by t.name'
exec (@query)
我实现的结果集的一部分
table Column 1 Column 2 Column 3
Veixxxxx cd_exxx cd_veixxx nr_apxxxxxx
Verxxxx cd_verxxx de_verxxx de_muxxxx
答案 4 :(得分:0)
做一个枢轴技巧......?
declare @max_cols int
declare @i int
declare @query as varchar(max)
declare @query2 as varchar(max)
select @max_cols = MAX(n)
from( select COUNT(COLUMN_NAME) as n
from INFORMATION_SCHEMA.COLUMNS
group by table_name
)V
select @i = 1, @query2 = ''
while @i <= @max_cols
begin
set @query2 = @query2 +', Col_'+CAST(@i as varchar(max))
set @i = @i+1
end
select @query2 = STUFF(@query2,1,1,'')
select @query =
'select *
from (
select T.TABLE_NAME,T.COLUMN_NAME,''Col_''+cast(T.ORDINAL_POSITION as varchar(max)) as pos
from INFORMATION_SCHEMA.COLUMNS T
)V
PIVOT (max(V.COLUMN_NAME) for pos in ('+@query2+'))U'
exec(@query)
实现的结果集与xml方法相同
TABLE_NAME Col_1 Col_2 Col_3
Veixxxxx cd_exxx cd_veixxx nr_apxxxxxx
Verxxxx cd_verxxx de_verxxx de_muxxxx