如何列出 VIEW 中列的源表名 (SQL Server 2005)
Posted
技术标签:
【中文标题】如何列出 VIEW 中列的源表名 (SQL Server 2005)【英文标题】:How to list the source table name of columns in a VIEW (SQL Server 2005) 【发布时间】:2012-08-17 06:47:41 【问题描述】:只是想知道如何在一个视图查询中列出列名和表名。
例如:
一个名为viewC
的视图,由tbl1 inner join tbl2
创建,包含a,b,c,d
列(a,b
来自tbl1
和c,d
来自tbl2
)。
如何
Select COLUMN_NAME, DATA_TYPE, column_default, character_maximum_length, sourceTableNAME
FROM information_schema.columns
where table_name='viewC'
一起?
【问题讨论】:
【参考方案1】:此信息可从INFORMATION_SCHEMA
视图中获得:
SELECT *
FROM INFORMATION_SCHEMA.VIEW_COLUMN_USAGE AS cu
JOIN INFORMATION_SCHEMA.COLUMNS AS c
ON c.TABLE_SCHEMA = cu.TABLE_SCHEMA
AND c.TABLE_CATALOG = cu.TABLE_CATALOG
AND c.TABLE_NAME = cu.TABLE_NAME
AND c.COLUMN_NAME = cu.COLUMN_NAME
WHERE cu.VIEW_NAME = '<your view name>'
AND cu.VIEW_SCHEMA = '<your view schema>'
如果您的视图包含来自多个数据库的表,则查询将变得相当复杂
【讨论】:
这显示列名和表名是的。但不会播种我的情况所需的别名。 是否有人能够找出查询以查看与基础表列名相关联的视图列别名?【参考方案2】:试试这个:
SELECT * FROM INFORMATION_SCHEMA.VIEW_COLUMN_USAGE AS VCU
JOIN INFORMATION_SCHEMA.COLUMNS AS COL
ON COL.TABLE_SCHEMA = VCU.TABLE_SCHEMA
AND COL.TABLE_CATALOG = VCU.TABLE_CATALOG
AND COL.TABLE_NAME = VCU.TABLE_NAME
AND COL.COLUMN_NAME = VCU.COLUMN_NAME
WHERE VCU.VIEW_NAME = 'ViewName'
See this SQLFiddle
【讨论】:
【参考方案3】:我有一个从另一个数据库读取的视图 (SQL Server 2012),也有一个 UNION。上面的查询对我不起作用,所以我决定使用 Profiler 检查 SSMS 如何检索信息。这就是我最终得到的结果:
SELECT
clmns.name AS [Name]
,usrt.name AS [DataType]
,CAST(CASE WHEN baset.name IN (N'nchar', N'nvarchar') AND clmns.max_length <> -1 THEN clmns.max_length/2 ELSE clmns.max_length END AS int) AS [Length]
,CAST(clmns.precision AS int) AS [NumericPrecision]
,CAST(clmns.scale AS int) AS [NumericScale]
,clmns.column_id AS [ID]
FROM sys.all_views AS v
INNER JOIN sys.all_columns AS clmns
ON clmns.object_id=v.object_id
LEFT OUTER JOIN sys.indexes AS ik
ON ik.object_id = clmns.object_id
AND 1=ik.is_primary_key
LEFT OUTER JOIN sys.types AS usrt
ON usrt.user_type_id = clmns.user_type_id
LEFT OUTER JOIN sys.types AS baset
ON (baset.user_type_id = clmns.system_type_id AND baset.user_type_id = baset.system_type_id)
OR ((baset.system_type_id = clmns.system_type_id) AND (baset.user_type_id = clmns.user_type_id) AND (baset.is_user_defined = 0) AND (baset.is_assembly_type = 1))
LEFT OUTER JOIN sys.xml_schema_collections AS xscclmns
ON xscclmns.xml_collection_id = clmns.xml_collection_id
WHERE v.[type] = 'V'
AND v.name ='<your view name>'
AND SCHEMA_NAME(v.schema_id)='<your schema name>'
ORDER BY [ID] ASC
【讨论】:
我需要获取有关系统视图中的列的信息,这是我可以开始工作的唯一答案!以上是关于如何列出 VIEW 中列的源表名 (SQL Server 2005)的主要内容,如果未能解决你的问题,请参考以下文章