How I can merge two identical databases in a range date specific?

300 Views Asked by At

I'm new in this world of SQL Server and I received one task to merge data tables in two identical SQL databases (SQL Server 2000), I have the same structure in both databases. The idea is to merge all old data tables until july-2020 (database1) in the new data tables (database2).

I think this is very simple activity but as I don't have experience with SQL Server. Please, could you help me?

I need to update tables in the SQL Database, my SQL database collecting data each 10min. I pasted below the Old DB (data until Jul-31-2020), New DB (data after Aug-10-2020) and the result New DB + Old DB.

Old DB  

Time                ActivePower
31-07-2020 23:40:00 19127100
31-07-2020 23:50:00 19127094
1/8/2020 0:00       NULL    
1/8/2020 0:10       NULL    
New DB  

Time                ActivePower
31-07-2020 23:40:00 NULL
31-07-2020 23:50:00 NULL
1/8/2020            19127086
1/8/2020 0:10       19127078
New DB + Old DB 

Time                ActivePower
31-07-2020 23:40:00 19127100
31-07-2020 23:50:00 19127094
1/8/2020            19127086
1/8/2020 0:10       19127078

screenshot

1

There are 1 best solutions below

0
user9601310 On

Following your example and assuming you are merging two tables (not databases) named "OldDB" and "NewDB" with just the two columns named Time and ActivePower, where Time is the unique identifier on each table, you will need to run two separate SQL statements (an UPDATE and an INSERT) to migrate the data from OldDB into NewDB (NOTE: this would be accomplished with a single SQL MERGE statement if you had SQL Server 2008 or later).

update newdb set newdb.activepower = olddb.activepower
from newdb 
inner join olddb on newdb.time = olddb.time 
where newdb.activepower is null;

insert into newdb 
select olddb.* from olddb 
left join newdb on newdb.time = olddb.time 
where newdb.time is null;

Additional Note: This is also assuming that you are only updating NewDB records that don't currently have a value for ActivePower.