简体   繁体   中英

Inserting data from one database to another conditionally

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)

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM