0

I have two tables with different database:

  • AccntID from table 'account' <--database name 'ECPNWEB'
  • AccountTID from table 'tblPolicy' <--database name 'GENESIS'

Now I want to insert 'tblPolicy' like this: <--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

Now what I want to do is to insert this "ONLY" to tblPolicy connected with the 'account' table with different database 'GENESIS'

Brian Tompsett - 汤莱恩
  • 5,753
  • 72
  • 57
  • 129

2 Answers2

1

You can select from two databases as shown below:

SELECT table1.SomeField, table2.SomeField
FROM   [ServerName1].[Database1].[dbo].[Table1] table1
       INNER JOIN [ServerName2].[Database2].[dbo].[Table2] table2
       ON table1.SomeField = table2.SomeField
Yaqub Ahmad
  • 27,569
  • 23
  • 102
  • 149
0

The key point is [ServerName].[DatabaseName].[databaseowner].[tableName]..i.e. Fully qualified name

This should work

;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 
Niladri Biswas
  • 4,153
  • 2
  • 17
  • 24