ms sql 获取表字段的属性

SELECT
    表名       = case when a.colorder=1 then d.name else '' end,
   
    字段名     = a.name,
    主键       = 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 '√' else '' end,
    类型       = b.name,
    占用字节数 = a.length,
    长度       = COLUMNPROPERTY(a.id,a.name,'PRECISION'),
    默认值     = isnull(e.text,'')
   
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

where
    d.name='TableName'    --如果只查询指定表,加上此条件

-------------------------------------------------------------------
SELECT

(case when a.colorder=1 then d.name else '' end) N'Table Name',

a.colorder N'Column SQ',

a.name N'Column Name',

(case when COLUMNPROPERTY( a.id,a.name,'IsIdentity')=1 then '√'else '' end) N'Idnetity FG',

(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) N'PK',

b.name N'Type',

a.length N'Bit Length',

COLUMNPROPERTY(a.id,a.name,'PRECISION') as N'Length',

isnull(COLUMNPROPERTY(a.id,a.name,'Scale'),0) as N'DataScale',

(case when a.isnullable=1 then '√'else '' end) N'Null',

isnull(e.text,'') N'Default'

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
--where d.name = 'tablename --如果只查询指定表,加上此条件
order by object_name(a.id),a.colorder

posted on 2010-01-27 16:24  梦回西夏  阅读(544)  评论(0编辑  收藏  举报