2012-08-17 75 views
5

想知道如何在一個查詢的列表中列出列名和表名。如何在VIEW中列出列的源表名(SQL Server 2005)

例如:

命名爲viewC,通過tbl1 inner join tbl2創建視圖,含有a,b,c,d列(a,btbl1c,dtbl2)。

如何

Select COLUMN_NAME, DATA_TYPE, column_default, character_maximum_length, sourceTableNAME 
FROM information_schema.columns 
where table_name='viewC' 

在一起嗎?

回答

8

該信息可從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

這說明列名和表名是。但不播種我的情況下需要的別名。 – 2013-08-24 13:26:37

+0

是否有人能夠找出查看與底層表列名稱綁定的視圖列別名的查詢? – AS91 2017-05-16 21:49:30

1

試試這個:

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

0

我有一個從另一個數據庫讀取並擁有UNION的視圖(SQL Server 2012)。上述查詢不適合我,所以我決定使用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 
相關問題