美文网首页数据存储
[关系型数据库][SQL Server]表和字段信息的查询

[关系型数据库][SQL Server]表和字段信息的查询

作者: jiedawang | 来源:发表于2019-03-22 21:37 被阅读0次

    最后一次更新日期: 2019/3/21

    使用到的系统表
    --数据库模式
    select * from sys.schemas
    --数据类型
    select * from sys.types
    --数据库对象
    select * from sys.objects
    --表字段
    select * from syscolumns
    select * from sys.columns
    --拓展属性
    select * from sys.extended_properties
    --索引
    select * from sys.indexes
    --索引字段
    select * from sys.index_columns
    --默认约束
    select * from sys.default_constraints
    
    查询表信息
    --表名,表描述,模式名,记录数
    SELECT so.name TableName,sep.value TableDesc,ss.name SchemaName,si2.rows [RowCount]
    FROM sys.objects so
    JOIN sys.schemas ss ON so.schema_id=ss.schema_id
    join sysindexes si2 on so.object_id=si2.id and si2.indid<2
    LEFT JOIN sys.extended_properties sep ON so.object_id=sep.major_id AND sep.minor_id=0 AND sep.name='MS_Description' 
    WHERE so.type='U' AND so.name<>'dtproperties' --AND so.name='Test'
    ORDER BY so.object_id
    
    查询字段信息
    --表名,字段名,字段描述,数据类型,长度,精度,小数位数,默认值,是否可空,
    --是否自增,是否唯一键,是否主键,索引名,索引类型,索引字段键序数
    select so.name TableName,sc.name ColumnName,sep.value ColumnDesc,
        st.name DataType,sc.max_length [DataLength],
        sc2.prec DataPrec,sc2.scale DataScale,sdc.definition DefaultValue,
        sc.is_nullable IsNullable,sc.is_identity IsIdentity,
        ISNULL(si.is_unique_constraint,0) IsUniqueKey,ISNULL(si.is_primary_key,0) IsPrimaryKey,
        si.name IndexName,si.type_desc IndexType,sic.key_ordinal IndexColumnKeyOrdinal
    from sys.objects so
    join sys.columns sc on so.object_id=sc.object_id
    join syscolumns sc2 on sc.object_id=sc2.id and sc.column_id=sc2.colid
    join sys.types st on sc.user_type_id=st.user_type_id
    left join sys.default_constraints sdc on sc.default_object_id=sdc.object_id
    left join sys.extended_properties sep on so.object_id=sep.major_id and sc.column_id=sep.minor_id and sep.name='MS_Description'
    left join sys.index_columns sic on sic.object_id=so.object_id and sic.column_id=sc.column_id
    left join sys.indexes si on sic.object_id=si.object_id and sic.index_id=si.index_id
    where so.type='U' AND so.name<>'dtproperties' --AND so.name='Test'
    order by so.object_id,sc.column_id
    

    相关文章

      网友评论

        本文标题:[关系型数据库][SQL Server]表和字段信息的查询

        本文链接:https://www.haomeiwen.com/subject/jcddvqtx.html