开发者

Getting View's Column Description

Is it a way to retrieve the view's column description from the base table (fn_listextendedproperty)?

The following syntax only list down the column name from the view

 SELECT *
   FROM sys.columns c
   JO开发者_JS百科IN sys.views v on c.OBJECT_ID = V.OBJECT_ID
   JOIN sys.schemas s ON s.schema_id = v.schema_id
                     and V.NAME = 'v_ProductInfo'


Finally i got the answer.

SELECT VIEW_COLUMN_NAME=c.name,VIEW_CATALOG,VIEW_SCHEMA,VIEW_NAME,TABLE_CATALOG,TABLE_SCHEMA,TABLE_NAME,COLUMN_NAME, ep.value as 'COLUMN_DESCRIPTION'
FROM sys.columns c
INNER JOIN sys.views vw on c.OBJECT_ID = vw.OBJECT_ID
INNER JOIN sys.schemas s ON s.schema_id = vw.schema_id
LEFT JOIN INFORMATION_SCHEMA.VIEW_COLUMN_USAGE vcu on vw.name = vcu.VIEW_NAME and s.name = vcu.VIEW_SCHEMA and c.name = vcu.COLUMN_NAME
LEFT JOIN (
    SELECT distinct SCM_Name=SCM.Name,TBL_Name=TBL.name,COLName=COL.name,COL_Object_id= COL.object_id,COL_column_id=COL.column_id
    FROM
    SYS.COLUMNS COL
    INNER JOIN SYS.TABLES TBL on COL.object_id = TBL.object_id
    INNER JOIN SYS.SCHEMAS SCM ON TBL.schema_id = SCM.schema_id) tempTBL on tempTBL.TBL_Name=vcu.TABLE_NAME and tempTBL.SCM_Name=TABLE_SCHEMA and tempTBL.COLName = vcu.COLUMN_NAME
Left join sys.extended_properties ep on tempTBL.COL_Object_id = ep.major_id and tempTBL.COL_column_id = ep.minor_id
where vw.NAME = 'v_ProductInfo'


This solution will fail if the view uses two columns from different tables with the same name

something like this:

Select
t1.Id,
t2.Id as 'T2Id'
From Table1 as t1
Inner Join Table2 as t2 On t1.SomeCol=t2.SomeOtherCol


Yes, You may use cte to retrieve the data.

Select * from (
    SELECT Row=ROW_NUMBER() over (PARTITION by vw.NAME,Column_id order by Column_id),IEW_COLUMN_NAME=c.name,VIEW_CATALOG,VIEW_SCHEMA,VIEW_NAME,TABLE_CATALOG,TABLE_SCHEMA,TABLE_NAME,COLUMN_NAME, ep.value as 'COLUMN_DESCRIPTION' 
    FROM sys.columns c
    INNER JOIN sys.views vw on c.OBJECT_ID = vw.OBJECT_ID
    INNER JOIN sys.schemas s ON s.schema_id = vw.schema_id
    LEFT JOIN INFORMATION_SCHEMA.VIEW_COLUMN_USAGE vcu on vw.name = vcu.VIEW_NAME and s.name = vcu.VIEW_SCHEMA and c.name = vcu.COLUMN_NAME 
    LEFT JOIN (
        SELECT distinct SCM_Name=SCM.Name,TBL_Name=TBL.name,COLName=COL.name,COL_Object_id= COL.object_id,COL_column_id=COL.column_id
        FROM
        SYS.COLUMNS COL
        INNER JOIN SYS.TABLES TBL on COL.object_id = TBL.object_id
        INNER JOIN SYS.SCHEMAS SCM ON TBL.schema_id = SCM.schema_id ) tempTBL on tempTBL.TBL_Name=vcu.TABLE_NAME and tempTBL.SCM_Name=TABLE_SCHEMA and tempTBL.COLName = vcu.COLUMN_NAME 
    Left join sys.extended_properties ep on tempTBL.COL_Object_id = ep.major_id and tempTBL.COL_column_id = ep.minor_id
    --where vw.name = 'vw_avm_allc'
) data
Where Row=1
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜