mengchew0113 mengchew0113 - 6 months ago 7
SQL Question

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
JOIN 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'

Answer

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'