使用规范化数据将具有平面数据的旧数据库复制到新数据库

时间:2013-01-31 21:40:59

标签: sql sql-server tsql

我有一个旧的数据库是一个单独的平面表。我想将旧数据复制到新的数据库结构。两者都是MSSQL数据库。这是我想要做的简化示例:

OLD_DB                                     New_DB

Customers_Table             Customers_Table         Phone_Numbers
---------------             --------------          -------------  
FirstName                   CustomerID              PhoneNumberID
LastName          -->       FirstName               CustomerID
PhoneNumber1                LastName                PhoneNumber
PhoneNumber2
PhoneNumber3

我了解如何复制平面数据。这似乎工作得很好:

INSERT INTO   New_DB.dbo.Customers_Table (FirstName, LastName)
SELECT        FirstName, LastName
FROM          OLD_DB.dbo.Customers_Table

我只是不知道如何将电话号码输入新结构。

2 个答案:

答案 0 :(得分:0)

如果您的FirstName和LastName是您的唯一标识符,则可以在运行上述语句后使用UNION运行此标识符:

INSERT INTO New_DB.dbo.Phone_Numbers (CustomerId, PhoneNumber)
SELECT C.CustomerID, OldC.PhoneNumber1
FROM New_DB.dbo.Customers_Table C
  JOIN OLD_DB.dbo.Customers_Table OldC ON C.FirstName = OldC.FirstName 
     AND C.LastName = OldC.LastName 
     AND OldC.PhoneNumber1 IS NOT NULL
UNION
SELECT C.CustomerID, OldC.PhoneNumber2
FROM New_DB.dbo.Customers_Table C
  JOIN OLD_DB.dbo.Customers_Table OldC ON C.FirstName = OldC.FirstName 
     AND C.LastName = OldC.LastName 
     AND OldC.PhoneNumber2 IS NOT NULL
UNION
SELECT C.CustomerID, OldC.PhoneNumber3
FROM New_DB.dbo.Customers_Table C
  JOIN OLD_DB.dbo.Customers_Table OldC ON C.FirstName = OldC.FirstName 
     AND C.LastName = OldC.LastName 
     AND OldC.PhoneNumber3 IS NOT NULL

或者,你可以使用UNPIVOT并运行这样的东西(我已将其浓缩用于测试,但概念相同):

SELECT Id, Phone 
FROM ( SELECT id, phone1, phone2, phone3 FROM Phone ) p
UNPIVOT
(Phone FOR Phones IN (phone1, phone2, phone3))AS Phone

以下是UNPIVOT的{​​{3}}:

祝你好运。

答案 1 :(得分:0)

选择电话号码,加入新公司表以获取ID(当然假设FirstName和LastName组合是唯一的),对三个电话号码的三个查询之间进行联合,然后插入新表:

insert into New_DB.dbo.Phone_Numbers

select c.CustomerID, o.PhoneNumber1
from New_DB.dbo.Customers_Table c
inner join OLD_DB.dbo.Customers_Table o
  on o.FirstName = c.FirstName and o.LastName = c.LastName
where o.PhoneNumber1 is not null

union all

select c.CustomerID, o.PhoneNumber2
from New_DB.dbo.Customers_Table c
inner join OLD_DB.dbo.Customers_Table o
  on o.FirstName = c.FirstName and o.LastName = c.LastName
where o.PhoneNumber2 is not null

union all

select c.CustomerID, o.PhoneNumber3
from New_DB.dbo.Customers_Table c
inner join OLD_DB.dbo.Customers_Table o
  on o.FirstName = c.FirstName and o.LastName = c.LastName
where o.PhoneNumber3 is not null

注意:如果客户在多个字段中拥有相同的电话号码,则会创建重复的电话号码。您可以使用union代替union all来删除这些重复项。