我试图找出创建 SQL 语句(在 SQL Server 中)以复制父记录和所有子记录的最佳方法。我以以下为例;
-- duplicate the order
insert into Orders (CustomerID, EmployeeID, OrderDate, RequiredDate,
ShippedDate, ShipVia, Freight, ShipName, ShipAddress,
ShipCity, ShipRegion, ShipPostalCode, ShipCountry)
select CustomerID, EmployeeID, getdate(), RequiredDate, null, ShipVia,
Freight, ShipName, ShipAddress, ShipCity, ShipRegion,
ShipPostalCode, ShipCountry
from Orders
where OrderID = @OrderID
-- find ID of duplicated order
declare @NewOrderID int;
select @NewOrderID = @@IDENTITY;
-- duplicate order details
insert into "Order Details" (OrderID, ProductID, UnitPrice,
Quantity, Discount)
select @NewOrderID, ProductID, UnitPrice, Quantity, Discount
from "Order Details"
where OrderID = @OrderID
这非常适合复制子表“订单详细信息”。但是我需要能够复制“订单详细信息”的子代,但看不到隔离每条记录的身份并传递给另一个表的方法。有没有人对如何轻松实现这一点有任何建议?