將SQL SERVER中所有表或某一個表的列資訊顯示出來

來源:互聯網
上載者:User

    正在作一個關於SQL SERVER資料庫的程式,要讀取資料庫中的列的資訊,從網上找了很多資料,終於找出來比較理想的sql語句,執行後返回的列分別是:表名、列名、列類型、列長度、列描述、是否主鍵,語句如下:

(如果只想操作一個表的,那麼把最後的%換成表名就可以了。)

SQLServer2000下能用:

 

SELECT SysObjects.Name as tb_name, SysColumns.Name as col_name, SysTypes.Name as col_type, SysColumns.Length as col_len, isnull(SysProperties.Value,SysColumns.Name) as col_memo,
case when SysColumns.name in
(select primarykey=a.name
FROM syscolumns a
 inner join sysobjects b on a.id=b.id  and b.xtype='U' and b.name<>'dtproperties'
 where  exists(SELECT 1 FROM sysobjects where xtype='PK' and name in (
 SELECT name FROM sysindexes WHERE indid in(
  SELECT indid FROM sysindexkeys WHERE id = a.id AND colid=a.colid
 )))
and b.name=SysObjects.Name
)
 then 1 else 0 end as is_key
 FROM SysObjects,SysTypes,SysColumns
LEFT JOIN SysProperties ON (Syscolumns.Id = Sysproperties.Id AND
 Syscolumns.Colid = Sysproperties.Smallid)
 WHERE (Sysobjects.Xtype ='u' OR Sysobjects.Xtype ='v')
AND Sysobjects.Id = Syscolumns.Id AND SysTypes.XType = Syscolumns.XType
AND SysTypes.Name <> 'sysname' AND Sysobjects.Name Like '%' ORDER By SysObjects.Name, SysColumns.colid

SQLServer2005下能用:

  SELECT sysobjects.Name as tb_name, syscolumns.Name as col_name, SysTypes.Name as col_type, syscolumns.Length as col_len, isnull(sys.extended_properties.Value,syscolumns.Name) as col_memo,
case when syscolumns.name in
(select primarykey=a.name
FROM syscolumns a
 inner join sysobjects b on a.id=b.id  and b.xtype='U' and b.name<>'dtproperties'
 where  exists(SELECT 1 FROM sysobjects where xtype='PK' and name in (
 SELECT name FROM sysindexes WHERE indid in(
  SELECT indid FROM sysindexkeys WHERE id = a.id AND colid=a.colid
 )))
and b.name=sysobjects.Name
)
 then 1 else 0 end as is_key
 FROM sysobjects,SysTypes,syscolumns
LEFT JOIN sys.extended_properties ON (Syscolumns.Id = sys.extended_properties.major_id AND
 Syscolumns.Colid = sys.extended_properties.minor_id)
 WHERE (sysobjects.Xtype ='u' OR Sysobjects.Xtype ='v')
AND Sysobjects.Id = Syscolumns.Id AND SysTypes.XType = Syscolumns.XType
AND SysTypes.Name <> 'sysname' AND Sysobjects.Name Like '%' ORDER By SysObjects.Name, SysColumns.colid

相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.