1

我有一个旧数据库,它是一个单一的平面表。我想将旧数据复制到新的数据库结构中。两者都是 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

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

4

2 回答 2

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

这是用于的SQL FiddleUNPIVOT

祝你好运。

于 2013-01-31T21:48:09.843 回答
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删除这些重复项。

于 2013-01-31T21:50:44.067 回答