SqlServer表結構查詢
阿新 • • 發佈:2018-12-30
Mysql資料庫查詢表結構很方便,用客戶端(SQLyog)可以直接複製出需要的表結構,據說可以用簡單的命令查詢表結構 desc 表結構
Sqlserver匯出表結構就很坑爹了,首先呢客戶端不支援,表設計頁面雖說可以複製表結構但是不包含欄位註釋,想想這種場景應該很常見不可能沒有解決方案的,於是在網上發現了一段指令碼,稍加調整就可以查詢出需要的表結構
指令碼及查詢示例
SELECT 表名 = CASE WHEN a.colorder = 1 THEN d.name ELSE '' END , 欄位說明 = ISNULL(g.[value], '') , 欄位名= a.name , 型別 = CASE WHEN b.name IN ( 'varchar', 'nvarchar' ) THEN b.name + '(' + CAST(COLUMNPROPERTY(a.id, a.name, 'PRECISION') AS VARCHAR(4)) + ')' WHEN b.name = 'decimal' THEN b.name + '(' +CAST(COLUMNPROPERTY(a.id, a.name, 'PRECISION') AS VARCHAR(4)) + ',' + CAST(COLUMNPROPERTY(a.id, a.name, 'Scale') AS VARCHAR(4)) + ')' ELSE b.name END FROM syscolumns a -- 列名 LEFT JOIN systypes b ONa.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 --預設值 LEFT JOIN sys.extended_properties g ON a.id = g.major_id AND a.colid = g.minor_id --擴充套件屬性(欄位說明) --LEFT JOIN sys.extended_properties f ON d.id = f.major_id AND f.minor_id = 0 --擴充套件屬性(表說明) WHERE d.name = 'SCM_Module' --可修改表名 ORDER BY a.id , a.colorder
比較全面的:
--快速查看錶結構(比較全面的) SELECT CASE WHEN col.colorder = 1 THEN obj.name ELSE '' END AS 表名, col.colorder AS 序號 , col.name AS 列名 , ISNULL(ep.[value], '') AS 列說明 , t.name AS 資料型別 , col.length AS 長度 , ISNULL(COLUMNPROPERTY(col.id, col.name, 'Scale'), 0) AS 小數位數 , CASE WHEN COLUMNPROPERTY(col.id, col.name, 'IsIdentity') = 1 THEN '√' ELSE '' END AS 標識 , CASE WHEN EXISTS ( SELECT 1 FROM dbo.sysindexes si INNER JOIN dbo.sysindexkeys sik ON si.id = sik.id AND si.indid = sik.indid INNER JOIN dbo.syscolumns sc ON sc.id = sik.id AND sc.colid = sik.colid INNER JOIN dbo.sysobjects so ON so.name = si.name AND so.xtype = 'PK' WHERE sc.id = col.id AND sc.colid = col.colid ) THEN '√' ELSE '' END AS 主鍵 , CASE WHEN col.isnullable = 1 THEN '√' ELSE '' END AS 允許空 , ISNULL(comm.text, '') AS 預設值 FROM dbo.syscolumns col LEFT JOIN dbo.systypes t ON col.xtype = t.xusertype inner JOIN dbo.sysobjects obj ON col.id = obj.id AND obj.xtype = 'U' AND obj.status >= 0 LEFT JOIN dbo.syscomments comm ON col.cdefault = comm.id LEFT JOIN sys.extended_properties ep ON col.id = ep.major_id AND col.colid = ep.minor_id AND ep.name = 'MS_Description' LEFT JOIN sys.extended_properties epTwo ON obj.id = epTwo.major_id AND epTwo.minor_id = 0 AND epTwo.name = 'MS_Description' WHERE obj.name = 'SCM_Module'--表名 ORDER BY col.colorder ;