如何:选择并插入父子记录而不在sql中使用循环

时间:2016-05-13 15:06:03

标签: sql select insert parent-child

我有两张桌子

OrderedStock
---
OrderID    Location
1          Richmond
2          Ohio
3          Queens


OrderItem
---
OrderItemID  OrderID   Name
1            1         Perfume
2            1         Blinds
3            2         Ball
4            3         Cabinet

如果我必须将这些表中的所有记录复制到类似的表(PostedOrder和PostedOrderItem),保留PostedOrderItem表中正确的PostedOrderId,那么最好的方法是什么。实际上,我在Order表中有大约45K行要复制,它们的嵌套OrderItem记录大约是200万。

目标表及其数据如下所示

PostedOrdered
---
PostedOrderID    Location
11               Richmond
12               Ohio
13               Queens


PostedOrderItem
---
PostedOrderItemID  PostedOrderID       Name
101                11                  Perfume
102                11                  Blinds
103                12                  Ball
104                13                  Cabinet

PostedOrderId和PostedOrderItemId是各自表中自动递增的主键。

我应该遵循任何最好的方法,而不用循环选择声明?

提前感谢并为大幅格式化道歉。

2 个答案:

答案 0 :(得分:0)

您可以使用两个基于数据透视表的插入选择

insert into aTempTable (OrderItemID, OrderID, Name, Location) 
select a.OrderItemID,  a.OrderID,   a.Name,  b.Location 
from OrderItem as a 
inner join OrderedStock as b on a.OrderID = b.OrderID;


insert into  PostedOrder (OrderID, Location) 
select distinct OrderID, Location 
from aTempTable ;


insert into PostedOrderItem (OrderItemID, OrderID, Name) 
select OrderItemID,  OrderID,   Name
from aTempTable ;

如果您需要新的OrderItemID,请使用此

insert into aTempTable ( OrderID, Name, Location) 
select    a.OrderID,   a.Name,  b.Location 
from OrderItem as a 
inner join OrderedStock as b on a.OrderID = b.OrderID;


insert into  PostedOrder (OrderID, Location) 
select distinct OrderID, Location 
from aTempTable ;


insert into PostedOrderItem ( OrderItemID, OrderID, Name) 
select OrderItemID,  OrderID,   Name
from aTempTable ;

答案 1 :(得分:0)

在“已发布订单”表格中,您还需要包含"原始ID"柱。您尚未指定如何生成新ID,因此我假设它是INT IDENTITY(1,1)列。

PostedOrder的示例表架构:

PostedOrderID INT IDENTITY(1,1) PRIMARY KEY NOT NULL,
Location VARCHAR(100),
OriginalID INT NOT NULL  /* This is the id from the original table  */

将记录插入此表:

INSERT INTO PostedOrder (Location,OriginalID)
SELECT Location, OrderID FROM OrderedStock

然后,您可以将原始ID用作链接,以获取PostedOrderID表的新PostedOrderItem

PostedOrderItem的示例表架构:

PostedOrderItemID INT IDENTITY(1,1) PRIMARY KEY NOT NULL,
PostedOrderID INT NOT NULL, /* foreign key to PostedOrder table */
Name VARCHAR(100)

注意:如果出于任何原因需要保留items表的原始ID,您还可以为其添加一列。您的插入没有必要。

将记录插入PostedOrderItem

INSERT INTO PostedOrderItem (PostedOrderID, Name)
SELECT p.PostedOrderID, o.Name
FROM PostedOrder p
INNER JOIN OrderItem o ON o.OrderID = p.OriginalID