1

所有...我需要一种方法来跨多个数据库查询相同的表。我有大约 30 多个数据库,它们都有相同的表。

    SELECT 
      a.name
      , a.address
      , b.company_id
      , c.part_no
      , c.cost
    FROM accounts a
    JOIN business b on a.whatever = b.whatever
    JOIN crazy c ON b.things = c.things

像这样简单的东西,但在所有数据库中。重点不是加入多个数据库,这很简单,它同时在所有数据库中运行。一定有比创建一个冗长的存储过程更简单的方法,不是吗?

4

3 回答 3

3
CREATE PROC dbo.alldatabasequery 
AS 

 CREATE TABLE #temp (
 databasename varchar(500),
 name varchar(max),
 address varchar(max),
 company_id varchar(max),
 cost varchar(max)
 )
INSERT INTO #temp 
 EXEC sp_MSforeachdb N'IF ''?'' NOT IN ( ''model'',''tempdb'',''master'',''msdb'')
  BEGIN 
  SELECT databasename=''?'' 
    , a.name
    , a.address
    , b.company_id
    , c.part_no
    , c.cost
    FROM ?.dbo.accounts a
    JOIN ?.dbo.business b 
    on a.whatever = b.whatever
    JOIN ?.crazy c
    ON b.things = c.things
   END' ; 

SELECT   * FROM #temp 


GO 

EXEC dbo.alldatabasequery 
于 2012-10-17T17:31:03.430 回答
0

试试这个

CREATE TABLE #temp (
 databasename varchar(500),
 name varchar(max),
 address varchar(max),
 company_id varchar(max),
 cost varchar(max)
 )


DECLARE @statement varchar(max)=''

     declare cur cursor FOR
 select name
   from master.dbo.sysdatabases
  where dbid >4

      open cur

 DECLARE @name  VARCHAR(8000)


      fetch next from cur into @name

      while @@fetch_status = 0

      begin

   SET @statement='SELECT databasename='''+@name+''', a.name
    , a.address
    , b.company_id
    , c.part_no
    , c.cost
    FROM '+@name+'.dbo.accounts a
    JOIN '+@name+'.dbo.business b 
    on a.whatever = b.whatever
    JOIN '+@name+'.crazy c
    ON b.things = c.things'

  INSERT INTO #temp 
  EXEC (@statement)
   fetch next from cur into @name
     end
    close cur
    deallocate cur

SELECT   * FROM #temp 
于 2012-10-17T20:46:38.777 回答
0

本文可能有您正在寻找的解决方案。

http://www.sqldbadiaries.com/2010/10/09/run-a-query-against-multiple-instances-using-ssms/

于 2012-10-17T21:17:01.177 回答