我正在尝试找出创建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
这非常适合复制子表“订单详细信息”。但我需要能够复制“订单详细信息”的子项,但看不到隔离每个记录的身份并传递到另一个表的方法。有没有人对如何轻松实现这一点有任何建议?
答案 0 :(得分:0)
要查找最新的身份证明信息,请尝试:
SELECT @NewOrderID=IDENT_CURRENT('tablename')
答案 1 :(得分:0)
您是否考虑过使用OUTPUT
条款?
如果你有兴趣,我可以添加一个例子