获取SQL Server表与字段信息的视图,适用于2005以上版本。
create view v_metadata as
SELECT
TableName = D.NAME,--表名
TableDesc = ISNULL(F.VALUE, ' '), --表说明
ColumnIndex = A.COLORDER, --字段序号
ColumnName = A.NAME, --字段名
IsIndentity = CASE WHEN COLUMNPROPERTY(A.ID,A.NAME, 'ISIDENTITY ')=1 THEN 'Yes 'ELSE ' ' END, --标识
IsKey = CASE WHEN EXISTS(SELECT 1 FROM SYSOBJECTS WHERE XTYPE= 'PK ' AND PARENT_OBJ=A.ID AND NAME IN (
SELECT NAME FROM SYSINDEXES WHERE INDID IN(
SELECT INDID FROM SYSINDEXKEYS WHERE ID = A.ID AND COLID=A.COLID))) THEN 'Yes ' ELSE ' ' END, --主键
DataType = B.NAME, --数据类型
ColumnByte = A.LENGTH, --占用字节数
ColumnLength = COLUMNPROPERTY(A.ID,A.NAME, 'PRECISION '), --长度
NumberLength = ISNULL(COLUMNPROPERTY(A.ID,A.NAME, 'SCALE '),0), --小数位数
[IsNull] = CASE WHEN A.ISNULLABLE=1 THEN 'Yes 'ELSE ' ' END, --允许为空
DefaultValue = ISNULL(E.TEXT, ' '), --默认值
ColumnDesc = ISNULL(G.[VALUE], ' ') --字段说明
FROM
SYSCOLUMNS A LEFT JOIN SYSTYPES B ON A.XUSERTYPE=B.XUSERTYPE
INNER JOIN SYSOBJECTS D ON A.ID=D.ID AND D.XTYPE= 'U ' AND D.NAME <> 'DTPROPERTIES '
LEFT JOIN SYSCOMMENTS E ON A.CDEFAULT=E.ID
LEFT JOIN sys.extended_properties G ON A.ID=G.major_id AND A.COLID=G.minor_id
LEFT JOIN sys.extended_properties F ON D.ID=F.major_id AND F.minor_id=0