代码改变世界

分享一个获取数据字典的Sql语句

2009-06-24 17:19  蓝之风  阅读(1873)  评论(0编辑  收藏  举报

前一阵子项目要验收文档,平时做项目时间紧没来得及将数据字典整理成一份完整的文档,当要验收的时候才整理,一点一点的整理真是太麻烦了,于是就写了一个小程序,可以从数据库中导出数据字典,可以导出如下4种格式:XML,HTML,Word,Excel,如果要使的导出的字典美观而有不需要改动的话要把每个字段的备注信息都写完整,这样导出来的文档不用做任何修改就可以提交给客户进行验收了。由于代码太乱了,暂时不好意思共享代码

在这个工具里的一个核心的sql语句:

Code

 

-- 数据字典
SELECT
        (case when a.colorder=1 then d.name else '' end)表名,
        a.colorder 字段序号,
        a.name 字段名,
        (case when COLUMNPROPERTY( a.id,a.name,'IsIdentity')=1 then ''else '' end) 标识,
       (case when (SELECT count(*)
        FROM sysobjects
        WHERE (name in
                (SELECT name
                FROM sysindexes
                WHERE (id = a.id) AND (indid in
                         (SELECT indid
                        FROM sysindexkeys
                        WHERE (id = a.id) AND (colid in
                                  (SELECT colid
                                 FROM syscolumns
                                 WHERE (id = a.id) AND (name = a.name))))))) AND
            (xtype = 'PK'))>0 then '' else '' end) 主键,
       b.name 类型,
       a.length 占用字节数,
      COLUMNPROPERTY(a.id,a.name,'PRECISION') as 长度,
      isnull(COLUMNPROPERTY(a.id,a.name,'Scale'),0) as 小数位数,
      (case when a.isnullable=1 then ''else '' end) 允许空,
      isnull(e.text,'') 默认值,
      isnull(g.[value],'') AS 字段说明
FROM  syscolumns  a left join systypes b
on  a.xtype=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.major_id
order by a.id,a.colorder