I have an old database that is a single flat table. I want to copy the old data to the new db structure. Both are MSSQL databases. Here’s a simplified example of what I want to do:
OLD_DB New_DB
Customers_Table Customers_Table Phone_Numbers
--------------- -------------- -------------
FirstName CustomerID PhoneNumberID
LastName --> FirstName CustomerID
PhoneNumber1 LastName PhoneNumber
PhoneNumber2
PhoneNumber3
I understand how to copy the flat data. This seems to work just fine:
INSERT INTO New_DB.dbo.Customers_Table (FirstName, LastName)
SELECT FirstName, LastName
FROM OLD_DB.dbo.Customers_Table
I just don’t know how to get the phone numbers into the new structure.
If your FirstName and LastName are your unique identifiers, you can run this using
UNIONafter you run your above statement:Alternatively, you could use
UNPIVOTand run something like this (I’ve condensed it for testing, but same concept):Here is the SQL Fiddle for the
UNPIVOT:Good luck.