有人可以帮我查询列出单个服务器中所有数据库中的所有表吗?
提前致谢。
答案 0 :(得分:3)
使用sp_MSforeachdb
遍历所有数据库,INFORMATION_SCHEMA.TABLES
查询每个数据库中的表:
sp_MSforeachdb 'USE [?]; SELECT * FROM INFORMATION_SCHEMA.TABLES'
答案 1 :(得分:1)
AS由here提出
尝试动态查询
您需要针对sys.tables
针对每个数据库进行查询。
select 'master' as DatabaseName,
T.name collate database_default as TableName
from master.sys.tables as T
union all
select 'tempdb' as DatabaseName,
T.name collate database_default as TableName
from tempdb.sys.tables as T
union all
select 'model' as DatabaseName,
T.name collate database_default as TableName
from model.sys.tables as T
union all
select 'msdb' as DatabaseName,
T.name collate database_default as TableName
from msdb.sys.tables as T
您可以使用sys.databases
动态构建和执行查询。
declare @SQL nvarchar(max)
set @SQL = (select 'union all
select '''+D.name+''' as DatabaseName,
T.name collate database_default as TableName
from '+quotename(D.name)+'.sys.tables as T
'
from sys.databases as D
for xml path(''), type).value('substring((./text())[1], 13)', 'nvarchar(max)')
--print @SQL
exec (@SQL)
答案 2 :(得分:0)
IF OBJECT_ID('tempdb.dbo.#tbl') IS NOT NULL
DROP TABLE #tbl
CREATE TABLE #tbl (
database_id SYSNAME
, tbl_name SYSNAME
, sch_name SYSNAME
, [rows] INT
)
DECLARE @SQL NVARCHAR(MAX)
SELECT @SQL = STUFF((
SELECT '
USE [' + d.name + ']
INSERT INTO #tbl
SELECT DB_NAME(), o.name, s.name, p.[rows]
FROM sys.objects o
JOIN sys.schemas s ON o.[schema_id] = s.[schema_id]
LEFT JOIN (
SELECT p.[object_id], [rows] = SUM(p.[rows])
FROM sys.partitions p
WHERE p.index_id < 2
GROUP BY p.[object_id]
) p ON p.[object_id] = o.[object_id]
WHERE o.[type] = ''U''
AND o.is_ms_shipped = 0;'
FROM sys.databases d
WHERE d.[state] = 0
FOR XML PATH(''), TYPE).value('.', 'NVARCHAR(MAX)'), 1, 2, '')
EXEC sys.sp_executesql @SQL
SELECT * FROM #tbl