在編寫SQL Server設(shè)計(jì)文檔的時(shí)候,需要描述各個(gè)表中各字段的屬性和描述等。那么,如何取得SQL Server表字段屬性呢?
一般的做法是在企業(yè)管理器中打開某個(gè)表,然后對(duì)這它各個(gè)SQL Server表字段的屬性,錄入到文檔中。這樣編寫一份數(shù)據(jù)庫(kù)設(shè)計(jì)文檔要花很多時(shí)間。有沒有更好的方法呢?
解決方法:其實(shí),SQL Server表、SQL Server表字段、索引、存儲(chǔ)過程和觸發(fā)器等等,都被稱為數(shù)據(jù)庫(kù)的對(duì)象。而關(guān)于這些對(duì)象的信息,都保存在SQL Server的系統(tǒng)表里面。我們可以通過查詢這些表,來(lái)獲取我們需要的數(shù)據(jù)庫(kù)對(duì)象的信息。對(duì)于表的字段,我們可以通過一下SQL語(yǔ)句查詢出它們的詳細(xì)信息:
- USE Northwind --數(shù)據(jù)庫(kù)
- SELECT
- (CASE WHEN a.colorder=1 THEN d.name ELSE '' END) N'表名',
- a.colorder N'字段序號(hào)',
- a.name N'字段名',
- (CASE WHEN COLUMNPROPERTY( a.id,a.name,'IsIdentity')=1 THEN '√'ELSE '' END) N'標(biāo)識(shí)',
- (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'主鍵',
- b.name N'類型',
- a.length N'占用字節(jié)數(shù)',
- COLUMNPROPERTY(a.id,a.name,'PRECISION') AS N'長(zhǎng)度',
- ISNULL(COLUMNPROPERTY(a.id,a.name,'Scale'),0) AS N'小數(shù)位數(shù)',
- (CASE WHEN a.isnullable=1 THEN '√'ELSE '' END) N'允許空',
- ISNULL(e.text,'') N'默認(rèn)值',
- ISNULL(g.[value],'') AS N'字段說(shuō)明'
- 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 sysproperties g on a.id=g.id AND a.colid=g.smallid
- WHERE
- d.name = 'Customers' --要查詢的表
- ORDER BY
- object_name(a.id), a.colorder
該文章在 2011/5/4 23:13:46 編輯過