將SQL SERVER中所有表的列資訊顯示出來
正在作一個關於SQL SERVER資料庫匯入Excel檔案的程式,要讀取資料庫中的列的資訊,從網上找了很多資料,終於總結出來比較理想的sql語句,執行後返回的列分別是:表名、列名、列類型、列長度、列描述、是否主鍵,語句如下:
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 主鍵=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
如果只想操作一個表的,那麼把最後的%換成表名就可以了。