Home > Enterprise >  Inserting data from one database to another conditionally
Inserting data from one database to another conditionally

Time:09-28

In my MSQL server I have a first database with a table that contains ID and Data columns, a second database, which is a copy of the first, except the Data column is empty.

I would like to transfer data from the first database into the second, inserting into the row with the corresponding ID. I would like the query to look something like this, but I'm not sure about the syntax

INSERT INTO db1.dbo.Table (Data)
    SELECT (Data) 
    FROM db2.dbo.Table
    WHERE db1.dbo.Table(ID) = db2.dbo.Table(ID)

CodePudding user response:

You can do an update on your second table like that:

UPDATE 
    t2
SET 
    t2.Data = t1.Data,
FROM 
    dbone.t1 AS t1
INNER JOIN dbtwo.t2 AS t2 ON t1.ID = t2.ID

If your second table is empty you can "copy" your data like that:

INSERT INTO dbone.t1 (ID, Data)
SELECT ID, Data
FROM dbtwo.t2
  •  Tags:  
  • sql
  • Related