从所有服务器数据库中的同一表中检索数据

时间:2016-09-11 00:32:42

标签: sql-server database data-retrieval multi-database

我有带有DB1,DB2,Db3的SQL Server 2012 ...> DB50

如果我需要在服务器中查看数据库,请使用

SELECT * FROM sys.databases   

除了五个没有此表的数据库外,所有数据库都有相同的表Saves

我需要知道哪些数据库有表Saves - 为此我使用

sp_msforeachdb "SELECT '?' DatabaseName, Name FROM ?.sys.Tables WHERE Name LIKE '%saves%'"

如果找到所有数据库,如何从表Saves检索数据?

我逐个使用,需要花费大量时间来保存

等数据
select * from db1.dbo.Saves

然后将数据保存回搜索

select * from db2.dbo.Saves

然后将数据保存回搜索

select * from db3.dbo.Saves

我需要一个SQL命令,如:

Select * from Saves in  sys.databases  if found

2 个答案:

答案 0 :(得分:0)

享受......

DECLARE @name  VARCHAR(50), -- database name  
        @Query  NVARCHAR(500) -- My Query

DECLARE db_cursor CURSOR FOR  
SELECT name 
FROM MASTER.dbo.sysdatabases 
WHERE name NOT IN ('master','model','msdb','tempdb')  

OPEN db_cursor   
FETCH NEXT FROM db_cursor INTO @name   

WHILE @@FETCH_STATUS = 0   
BEGIN 
set @Query ='USE  '+@name+' 
            Go 
            if OBJECT_ID(''['+@name+'].[dbo].[saves]'') is not null
            begin
                select * from ['+@name+'].[dbo].[saves]
            end
            else
            begin
                select ''table saves does not exist into database: '+@name+''' 
            end'

/* the next line for resloving error : Incorrect syntax near 'Go'*/
SET @Query = 'EXEC (''' + REPLACE(REPLACE(@Query, '''', ''''''), 'GO', ''');     EXEC(''') + ''');'--Just add this one line.

exec sp_executesql @Query

FETCH NEXT FROM db_cursor INTO @name   
END   

CLOSE db_cursor   
DEALLOCATE db_cursor  

答案 1 :(得分:0)

您可以使用以下查询结果。

EXEC sp_msforeachdb '
USE [?];
IF EXISTS (SELECT * FROM [?].INFORMATION_SCHEMA.TABLES AS T WHERE T.TABLE_NAME=''Saves'')
BEGIN
DECLARE @QUERY VARCHAR(MAX);
SELECT @QUERY = COALESCE(@QUERY+'';
SELECT ''''?'''' AS DBNAME; SELECT ''''?'''' AS DBNAME,* FROM [''+T.TABLE_CATALOG+''].''+''[''+T.TABLE_SCHEMA+'']''+''.[''+T.TABLE_NAME+'']'',''
SELECT ''''?'''' AS DBNAME;
SELECT ''''?'''' AS DBNAME,* FROM [''+T.TABLE_CATALOG+''].''+''[''+T.TABLE_SCHEMA+'']''+''.[''+T.TABLE_NAME+'']'')
FROM [?].INFORMATION_SCHEMA.TABLES T WHERE T.TABLE_NAME = ''Saves''
EXEC (@QUERY);
END
';

`