6

只是想知道如何在一个视图查询中列出列名和表名。

例如:

一个名为viewCcreate by的视图tbl1 inner join tbl2,包含a,b,c,d列(a,bfromtbl1c,dfrom tbl2)。

如何

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

一起?

4

3 回答 3

12

此信息可从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>'

如果您的视图包含来自多个数据库的表,则查询将变得相当复杂

于 2012-08-17T07:44:22.737 回答
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'

看到这个 SQLFiddle

于 2012-08-17T07:14:28.653 回答
1

我有一个从另一个数据库读取的视图(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
于 2016-10-24T08:28:13.633 回答