How to better duplicate a set of data in SQL Server

前端 未结 3 652
小蘑菇
小蘑菇 2020-12-21 00:29

I have several related tables that I want to be able to duplicate some of the rows while updating the references.

I want to duplicate a row in Table1, and all of

3条回答
  •  误落风尘
    2020-12-21 00:37

    Why dont you join on the FruitName to get a table with old and new FruitId's? Considering information would be added at the same time.... it may not be the best option but you wont be using any cycles.

    INSERT INTO BASKET(BASKETNAME)
    VALUES ('COPY BASKET')
    
    DECLARE @iBasketId int
    SET @iBasketId = @@SCOPE_IDENTITY;
    
    
    insert into Fruit (BasketId, FruitName)
    select @iBasketId, FruitName
    from Fruit 
    where BasketId = @originalBasket
    
    declare @tabFruit table (originalFruitId int, newFruitId int)
    
    insert into @tabFruit (originalFruitId, newFruitId)
    select o.FruitId, n.FruitId
    from (SELECT FruitId, FruitName from Fruit where BasketId = @originalBasket) as o
    join (SELECT FruitId, FruitName from Fruit where BasketId = @newBasket) as n
        on o.FruitName = n.FruitName
    
    
    insert into Property (FruitId, PropertyText)
    select NewFruitId, PropertyText
    from Fruit f join @tabFruit t on t.originalFruitId = f.FruitId
    

提交回复
热议问题