Using merge..output to get mapping between source.id and target.id

后端 未结 2 665
隐瞒了意图╮
隐瞒了意图╮ 2020-11-22 00:13

Very simplified, I have two tables Source and Target.

declare @Source table (SourceID int identity(1,2), SourceName varchar(50))
declare @Target table (Targe         


        
2条回答
  •  小鲜肉
    小鲜肉 (楼主)
    2020-11-22 01:08

    I would like to add another example to add to @Nathan's example, as I found it somewhat confusing.

    Mine uses real tables for the most part, and not temp tables.

    I also got my inspiration from here: another example

    -- Copy the FormSectionInstance
    DECLARE @FormSectionInstanceTable TABLE(OldFormSectionInstanceId INT, NewFormSectionInstanceId INT)
    
    ;MERGE INTO [dbo].[FormSectionInstance]
    USING
    (
        SELECT
            fsi.FormSectionInstanceId [OldFormSectionInstanceId]
            , @NewFormHeaderId [NewFormHeaderId]
            , fsi.FormSectionId
            , fsi.IsClone
            , @UserId [NewCreatedByUserId]
            , GETDATE() NewCreatedDate
            , @UserId [NewUpdatedByUserId]
            , GETDATE() NewUpdatedDate
        FROM [dbo].[FormSectionInstance] fsi
        WHERE fsi.[FormHeaderId] = @FormHeaderId 
    ) tblSource ON 1=0 -- use always false condition
    WHEN NOT MATCHED
    THEN INSERT
    ( [FormHeaderId], FormSectionId, IsClone, CreatedByUserId, CreatedDate, UpdatedByUserId, UpdatedDate)
    VALUES( [NewFormHeaderId], FormSectionId, IsClone, NewCreatedByUserId, NewCreatedDate, NewUpdatedByUserId, NewUpdatedDate)
    
    OUTPUT tblSource.[OldFormSectionInstanceId], INSERTED.FormSectionInstanceId
    INTO @FormSectionInstanceTable(OldFormSectionInstanceId, NewFormSectionInstanceId);
    
    
    -- Copy the FormDetail
    INSERT INTO [dbo].[FormDetail]
        (FormHeaderId, FormFieldId, FormSectionInstanceId, IsOther, Value, CreatedByUserId, CreatedDate, UpdatedByUserId, UpdatedDate)
    SELECT
        @NewFormHeaderId, FormFieldId, fsit.NewFormSectionInstanceId, IsOther, Value, @UserId, CreatedDate, @UserId, UpdatedDate
    FROM [dbo].[FormDetail] fd
    INNER JOIN @FormSectionInstanceTable fsit ON fsit.OldFormSectionInstanceId = fd.FormSectionInstanceId
    WHERE [FormHeaderId] = @FormHeaderId
    

提交回复
热议问题