假设我们的层次结构由多个对象组成,如下所示:
我想复制这棵树(也许会以某种方式改变这些对象)。
执行此操作的一种简单方法是在对象之间进行迭代并逐个创建。但这里的表现很差。另外,我不喜欢循环; - )
所以问题 - 是否可以使用基于集合的逻辑?
答案 0 :(得分:3)
使用this question中描述的技术,您可以执行以下操作:
DECLARE @CartId int, @NewCartId int;
DECLARE @CartItems TABLE (OldId int, NewId int);
SET @CartId = ...;
INSERT INTO Shopping_Cart (
Session_Id_Str,
Name,
Program_User_Id,
Shopping_Cart_Status_Code,
Placed_Order_Id)
SELECT
Shopping_Cart_Id,
Session_Id_Str,
Name,
Program_User_Id,
Shopping_Cart_Status_Code,
Placed_Order_Id
FROM Shopping_Cart
WHERE Shopping_Cart_Id = @CartId;
SET @NewCartId = SCOPE_IDENTITY();
WITH src AS (
SELECT
Shopping_Cart_Item_Id,
@NewCartId AS Shopping_Cart_Id,
Base_Product_Id,
Product_Category_Id,
Shop_Id,
Currency_Code
FROM Shopping_Cart_Item
WHERE Shopping_Cart_Id = @CartId
)
MERGE Shopping_Cart_Item AS tgt
USING src
ON 0 = 1
WHEN NOT MATCHED THEN
INSERT (
Shopping_Cart_Id,
Base_Product_Id,
Product_Category_Id,
Shop_Id,
Currency_Code)
VALUES (
src.Shopping_Cart_Id,
src.Base_Product_Id,
src.Product_Category_Id,
src.Shop_Id,
src.Currency_Code)
OUTPUT
src.Shopping_Cart_Item_Id,
inserted.Shopping_Cart_Item_Id
INTO @CartItems (OldId, NewId);
WITH src AS (
SELECT
s.Shopping_Cart_Item_Detail_Id,
map.NewId AS Shopping_Cart_Item_Id,
s.Display_Order_Number,
s.Product_Id,
s.Product_Variant_Id
FROM Shopping_Cart_Item_Detail s
INNER JOIN @CartItems map ON s.Shopping_Cart_Item_Id = map.OldId
)
MERGE Shopping_Cart_Item_Detail AS tgt
USING src
ON 0 = 1
WHEN NOT MATCHED THEN
INSERT (
Shopping_Cart_Item_Id,
Display_Order_Number,
Product_Id,
Product_Variant_Id)
VALUES (
src.Shopping_Cart_Item_Id,
src.Display_Order_Number,
src.Product_Id,
src.Product_Variant_Id);
假设您只想一次复制一个“树”。
这一切都应该在一次交易中完成。