2016-12-13 89 views
2

我有一個服務器中的10個數據庫,是否有可能查詢所有這些數據庫中的表?從所有服務器獲取表

select * from master..sysobjects where name ='table' 

回答

0

您可以使用下面的SQL來獲取每個數據庫的所有表。您可以編輯SQL在@SQL參數得到的東西每個數據庫別的,如果你想

DECLARE @databaseName VARCHAR(30) 


DECLARE @TABLES TABLE ([Database] VARCHAR(MAX), [Table_Name] VARCHAR(MAX)) 

DECLARE [DBs] CURSOR FOR 
SELECT name FROM sys.databases 


OPEN [DBs] 
FETCH NEXT FROM [DBs] INTO @databaseName 

WHILE @@FETCH_STATUS = 0 
BEGIN 

     DECLARE @SQL VARCHAR(MAX) = 'SELECT ''' + @databaseName +''' as [Database], Name FROM ['+ @databaseName +'].sys.tables' 

     INSERT INTO @TABLES 
     EXEC (@SQL) 

     FETCH NEXT FROM [DBs] INTO @databaseName 
END 

CLOSE [DBs] 
DEALLOCATE [DBs] 

SELECT * FROM @TABLES 
0

您可以使用以下步驟

Declare @str nvarchar(max) 
Select name into #temp from sys.databases 
Select 'Select name from '+name+'.sys.tables' AS statements into #temp1 from #temp 
Set @str=(Select distinct Stuff((Select ' '+statements from #temp1 for xml path('')),1,1,'') from #temp1) 

Exec (@str) 

請回復我。在此

相關問題