在SQL Server中,我希望在数据库中看到Table_Name和与该Table_Name关联的所有列。所以输出应该是这样的:
TABLE_NAME COLUMN_NAME
1. Employee Employee-id, Lastname, Firstname, Title...........
2. Orders Orderid, Order-date, shipped-date, delivery-date.......
3. Products Product-id, Product-name, supplier-id, category-id.....
4. Suppliers Supplier-id, Company-name, contact-name.......
5. ............................................................
6. ...................................................
(So on....)
是否可以使用WHILE LOOP或任何其他方式获得上述结果?如果是,您可以发布代码。
另外,我尝试使用Temp Table:
来解决这个问题 create table #hello
(table_name1 Varchar(max))
insert into #hello(table_name1)
select table_name from information_schema.columns
GO
create table #hello2
(table_name2 varchar(max),column_name2 varchar(max))
insert into #hello2(table_name2 ,column_name2)
select table_name,column_name from information_schema.columns
GO
select a.table_name1,b.column_name from #hello a inner join
information_schema.columns b
on a.table_name1=b.table_name COLLATE Latin1_general_CI_AS
order by table_name
GO
我成功列出了垂直列但我无法得到以逗号分隔的列列表。
答案 0 :(得分:18)
Select TABLE_SCHEMA, TABLE_NAME
, Stuff(
(
Select ', ' + C.COLUMN_NAME
From INFORMATION_SCHEMA.COLUMNS As C
Where C.TABLE_SCHEMA = T.TABLE_SCHEMA
And C.TABLE_NAME = T.TABLE_NAME
Order By C.ORDINAL_POSITION
For Xml Path('')
), 1, 2, '') As Columns
From INFORMATION_SCHEMA.TABLES As T
如评论中所述,上述内容将包含观点。如果要排除视图,可以执行以下操作:
Select T.TABLE_SCHEMA, T.TABLE_NAME
, Stuff(
(
Select ', ' + C.COLUMN_NAME
From INFORMATION_SCHEMA.COLUMNS As C
Where C.TABLE_SCHEMA = T.TABLE_SCHEMA
And C.TABLE_NAME = T.TABLE_NAME
Order By C.ORDINAL_POSITION
For Xml Path('')
), 1, 2, '') As Columns
From INFORMATION_SCHEMA.TABLES As T
Left Join INFORMATION_SCHEMA.VIEWS As V
On V.TABLE_SCHEMA = T.TABLE_SCHEMA
And V.TABLE_NAME = T.TABLE_NAME
Where V.TABLE_NAME Is Null
答案 1 :(得分:5)
select name as TABLE_NAME,
STUFF(COLUMN_NAME, 1, 1, '') AS COLUMN_NAME
from sys.tables t
CROSS APPLY
(
SELECT
',' + name AS [text()]
FROM
sys.columns c
WHERE
c.object_id = t.object_id
FOR XML PATH('')
) o (COLUMN_NAME)
答案 2 :(得分:0)
由于您的问题提到了数据库中的 ,而不是使用信息模式,因此我使用了数据库:
select t.name,
STUFF ((
select ',' + c.name
from TEST_DB.sys.columns c
join TEST_DB.sys.tables tt on tt.object_id = t.object_id and t.object_id = c.object_id
join TEST_DB.sys.schemas s on tt.schema_id = s.schema_id
order by t.name, c.column_id
for xml path('')), 1, 1, '') as columns
from TEST_DB.sys.tables t
where t.name = 'PutTableNameHere if you want to filter'
为特定数据库中的所有表保留where子句。