ms sql 獲取表欄位的屬性

iSQlServer發表於2010-01-28

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

來自 “ ITPUB部落格 ” ,連結:http://blog.itpub.net/16436858/viewspace-626229/,如需轉載,請註明出處,否則將追究法律責任。

相關文章