用于复制父记录和子记录的SQL

时间:2013-07-31 14:58:47

标签: sql-server tsql parent-child duplicate-data

我正在尝试找出创建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

这非常适合复制子表“订单详细信息”。但我需要能够复制“订单详细信息”的子项,但看不到隔离每个记录的身份并传递到另一个表的方法。有没有人对如何轻松实现这一点有任何建议?

2 个答案:

答案 0 :(得分:0)

要查找最新的身份证明信息,请尝试:

SELECT @NewOrderID=IDENT_CURRENT('tablename')

答案 1 :(得分:0)

您是否考虑过使用OUTPUT条款? 如果你有兴趣,我可以添加一个例子