跨多个数据库查询表

时间:2012-10-17 17:22:42

标签: sql sql-server-2008

全部...我需要一种方法来跨多个数据库查询相同的表。我有大约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

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

3 个答案:

答案 0 :(得分: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 

答案 1 :(得分: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 

答案 2 :(得分:0)