Sql-server – Consolidating 2 Tables with same Values

duplicationmigrationsql server

I am working on a project trying to consolidate two databases, DB1 and DB2, for my organization into a single database, DB3.

Initially our organization started with DB1. A few years back they made a new database called DB2 and moved on to using only DB2.

Currently, I am working on the Orders Table.

Since new rows were inserted into DB2 without importing existing rows from DB1, Order-id Column values started from 1 instead of continuing from where the Order-id Column in DB1 had ended.

I have many Order-id Column values that are the same in both Tables that represent different orders.

For example Order-id = 100 in DB1 refers to order "X", whereas Order-id = 100 in DB2 refers to order "Y".

If I insert rows from both DB1.Orders and DB2.Orders into DB3.Orders there will be duplicate rows representing different orders.

As I have not come across this sort of situation before, I need a suggested approach for dealing with this.

Best Answer

Sometimes, the lack of an uint type in SQL Server can come in handy. If Order-id is defined as identity(1,1) in DB2, you likely do not have any negative Order-ids.

Consider importing all the legacy DB1..Orders.Order-id fields as the same number, but multiplied by -1. If there's a FK to Order-id in DB1, you would use the same multiple-by-negative-one conversion when those records are loaded into their corresponding tables in DB2.

With this method, you also have the benefit of easily identifying the legacy orders originally from DB1 because their Order-id is always negative (just be sure to document this.)

Edit - added an example

-- Assumptions:
-- DB1 and DB2 are on the same server
-- The table Orders is in the dbo schema
-- Order-id is an integer-type in DB1 and DB2
-- Order-id >= 0 in DB1 and DB2
-- Order-id is an identity(a, b), where a and b >=0 in DB2

-- Overview: Insert records from DB1 into DB2, but reverse the
-- sign of Order-id (i.e., positive to negative).

Use DB2
Go

Set Identity_Insert dbo.Orders On;

Insert dbo.Orders
(Order-id, col2, col3)

Select (-1 * Order-id), col2, col3
From DB1.dbo.Orders;

Set Identity_Insert dbo.Orders Off;
Go

-- Have related records? Insert them here.