查询某个数据库下所有用户数据表名及各数据表字段信息

时间:2021-11-29 12:26:40

因业务需要查询数据库中所有数据表名和各个数据表的字段信息,百度了很久

要么是“查询某个数据库下的所有数据表”,要么就是“查询某个数据表下的所有字段信息”

只能自己动手改造了。。。

记录下,指不定哪天又要用到

WITH TABLE_INFO AS (
SELECT 
(SELECT CC.NAME FROM [服务器].[数据库].[dbo].SYSOBJECTS CC WHERE CC.ID=ZDM.ID)AS tablename,
ZDM.NAME AS 字段名,
(SELECT TOP 1 LX.name  FROM [服务器].[数据库].[dbo].SYSTYPES LX WHERE LX.XTYPE=ZDM.xusertype)AS ziduanmane,
ZDM.length AS 长度
FROM [服务器].[数据库].[dbo].SYSCOLUMNS ZDM 
WHERE ZDM.ID IN 
(SELECT BM.ID FROM [服务器].[数据库].[dbo].SYSOBJECTS BM WHERE BM.XTYPE='U') 
)
SELECT * FROM TABLE_INFO ORDER BY tablename

 例子1:--1.查询master数据库下所有数据表的字段信息

WITH TABLE_INFO AS (
SELECT 
(SELECT CC.NAME FROM master.[dbo].SYSOBJECTS CC WHERE CC.ID=ZDM.ID)AS tablename,
ZDM.NAME AS 字段名,
(SELECT TOP 1 LX.name FROM master.[dbo].SYSTYPES LX WHERE LX.XTYPE=ZDM.xusertype)AS ziduanmane,
ZDM.length AS 长度
FROM master.[dbo].SYSCOLUMNS ZDM 
WHERE ZDM.ID IN 
(SELECT BM.ID FROM master.[dbo].SYSOBJECTS BM WHERE BM.XTYPE='U') 
)
SELECT * FROM TABLE_INFO ORDER BY tablename

  例子2:--2.查询master数据库指定表前缀的字段信息

 

WITH TABLE_INFO AS (
SELECT 
(SELECT CC.NAME FROM  master.[dbo].SYSOBJECTS CC WHERE CC.ID=ZDM.ID)AS tablename,
ZDM.NAME AS 字段名,
(SELECT TOP 1 LX.name  FROM master.[dbo].SYSTYPES LX WHERE LX.XTYPE=ZDM.xusertype)AS ziduanmane,
ZDM.length AS 长度
FROM master.[dbo].SYSCOLUMNS ZDM 
WHERE ZDM.ID IN 
(SELECT BM.ID FROM master.[dbo].SYSOBJECTS BM WHERE BM.XTYPE='U' AND BM.Name like'sc%')--增加数据库表前缀过滤 
)
SELECT * FROM TABLE_INFO ORDER BY tablename