博客园  :: 首页  :: 新随笔  :: 联系 :: 订阅 订阅  :: 管理

列出SQL SERVER 数据库所有表信息的sql 语句

Posted on 2005-09-21 16:03  sashow  阅读(862)  评论(0编辑  收藏  举报
 1select 
 2     ( case when a.colorder = 1 then d.name else '' end ) 表名,
 3     a.colorder 字段序号,
 4     a.name 字段名,
 5     ( case when COLUMNPROPERTY (a.id,a.name,'isidentity'= 1 then '' else '' end ) 标识,
 6     ( case when ( 
 7            select count(*from sysobjects
 8                where name in (
 9                    select name from sysindexes
10                    where (id = a.id ) and ( indid in 
11                        (select indid from sysindexkeys where
12                            ( id = a.id ) and ( colid in (
13                                select colid from syscolumns
14                                    where ( id = a.id ) and ( name = a.name ))))))
15                    and ( xtype ='PK')) > 0 then '' else '' end ) 主键,
16    b.name 类型,
17    a.length 字节数,
18    COLUMNPROPERTY ( a.id,a.name ,'PRECISION' ) as 长度,
19    isnull ( COLUMNPROPERTY ( a.id,a.name ,'Scale'),0as 小数位数,
20    (case when a.isnullable = 1 then '' else '' end ) 允许空,
21    isnull ( e.text,'') 默认值,
22    isnull (g.[value],'' ) as 字段说明
23from syscolumns a left join systypes b
24on a.xtype = b.xusertype
25inner join sysobjects d
26on a.id = d.id and d.xtype='U' and d.name <> 'dtproperties'
27left join syscomments e
28on a.cdefault = e.id
29left join sysproperties g
30on a.id = g.id and a.colid = g.smallid
31order by a.id ,a.colorder


从这个 sql 语句我学到的东西:
1、case when ... then ... else ... end  :选择语句用在 select 语句中,可以将原来用0,1这样的描述信息,转换为实际的含义,而不要在程序中根据查询出来的结果再进行判断。这个可以理解为简单的数据格式化吧。如这条sql 语句中出现的 case when a.isnullable = 1 then '√' else '' end  将数据库从存储的 0,1 转换为了 '√' 和'';

2、left join :使用这种连接方式可以使查询结果描述出一种包含关系。

3、isnull 函数:ISNULL ( check_expression , replacement_value ) ,作用是使用指定的替换值替换 NULL,例如下面的 SQL 语句中如果一本书的名称为 null ,则将价格设置为 0.00。

1SELECT SUBSTRING(title, 115AS Title, type AS Type, 
2   ISNULL(price, 0.00AS Price
3FROM titles
4


4、当然,最重要的是学到这个列出数据库表信息(包括表名、字段名、是否标识、是否主键、字段类型、字节数、长度、小数位数、允许空、默认值、字段说明)的 SQL 语句。^_^