如何从数据库检索表的记录到另一个数据库

时间:2012-10-25 01:22:33

标签: sql database stored-procedures sql-server-2005

我有两个不同数据库的表:

  • 表'account'中的AccntID< - 数据库名称'ECPNWEB'
  • 表'tblPolicy'中的AccountTID< - 数据库名称'GENESIS'

现在我想像这样插入'tblPolicy':< - database'GENESIS'

  INSERT INTO dbo.tblPolicy
      ( 

        PolicyID                 ,
        AccountTID               ,
        DistributorID            ,
        CARDNAME                 ,
        DENOMINATION             ,
        RETAILPRICE              ,
        COSTPAYABLE              ,
        ECPAYFEES                ,
        PLUCODE 

      ) 
-- Insert statements for procedure here


select t.* from
(Select  AccountTID=@AccntID, DistributorID=@DistributorID, CARDNAME=@CARDNAME, DENOMINATION=@DENOMINATION, RETAILPRICE=@RETAILPRICE, COSTPAYABLE=@COSTPAYABLE, ECPAYFEES=@ECPAYFEES, PLUCODE=@PLUCODE) t,
account a
where a.AccntID = t.AccountTID --for account

现在我要做的是将这个“ONLY”插入到与'account'表连接的tblPolicy中,并使用不同的数据库'GENESIS'

2 个答案:

答案 0 :(得分:1)

您可以从两个数据库中进行选择,如下所示:

SELECT table1.SomeField, table2.SomeField
FROM   [ServerName1].[Database1].[dbo].[Table1] table1
       INNER JOIN [ServerName2].[Database2].[dbo].[Table2] table2
       ON table1.SomeField = table2.SomeField

答案 1 :(得分:0)

关键点是[ServerName]。[DatabaseName]。[databaseowner]。[tableName] ..即。完全限定名称

这应该有效

;With Cte As
(
    Select AccountTID=@AccntID
    , DistributorID=@DistributorID
    , CARDNAME=@CARDNAME
    , DENOMINATION=@DENOMINATION
    , RETAILPRICE=@RETAILPRICE
    , COSTPAYABLE=@COSTPAYABLE
    , ECPAYFEES=@ECPAYFEES
    , PLUCODE=@PLUCODE
)

INSERT INTO GENESIS..dbo.tblPolicy
  ( 
    PolicyID                 ,
    AccountTID               ,
    DistributorID            ,
    CARDNAME                 ,
    DENOMINATION             ,
    RETAILPRICE              ,
    COSTPAYABLE              ,
    ECPAYFEES                ,
    PLUCODE 

  ) 

Select t.*
From Cte t,ECPNWEB..account a WITH (NOLOCK) 
where a.AccntID = t.AccountTID