Delimiter //
/**
 * move entries and accounts ref data from one entity to another
 * must be call after PS BUSINESS_ENTITIES_COPY_REF_DATA
 * -> use table TMP_ENTTCP_REFDATAS_SRC created by PS BUSINESS_ENTITIES_COPY_REF_DATA
 * @author Armen
 */
Drop Procedure if Exists BUSINESS_ENTITIES_MOVE_REF_DATA//

Create Procedure BUSINESS_ENTITIES_MOVE_REF_DATA(
    In srcEntityId Int Unsigned
    , In tarEntityId Int Unsigned
    , In inTransaction smallint
)
Begin
    bemrd_Main: begin
        Declare bemrd_transactionStarted int default 0 ;
        DECLARE Exit HANDLER FOR SQLEXCEPTION
            Begin
                if bemrd_transactionStarted  <> 0 then
                    rollback;
                    set bemrd_transactionStarted  = 0;
                End if;
                resignal;
            end ;
        if Coalesce(inTransaction, 0) = 0 Then
            Start Transaction;
            Set bemrd_transactionStarted  = 1;
        else
            Set bemrd_transactionStarted  = 0;
        end if;

        Set @bemrd_srcEntityId = srcEntityId;
        Set @bemrd_tarEntityId = tarEntityId;
        bemrd_accupdt: BEGIN
            -- explain
            Update
                ACC_REF_DATAS tar
                Inner Join TMP_ENTTCP_REFDATAS_SRC src
                    On tar.ENT_REF_DATAS_ID_ENT_REF_DATAS = src.SRC_ID_ENTITIES_REF_DATAS
            Set
                tar.ENT_REF_DATAS_ID_ENT_REF_DATAS = src.TAR_ID_ENTITIES_REF_DATAS
            ;
        end ;
        bemrd_entupdt: BEGIN
            -- explain
            Update
                ENTRIES_REF_DATAS tar
                Inner Join TMP_ENTTCP_REFDATAS_SRC src
                    On tar.ENT_REF_DATAS_ID_ENT_REF_DATAS = src.SRC_ID_ENTITIES_REF_DATAS
            Set
                tar.ENT_REF_DATAS_ID_ENT_REF_DATAS = src.TAR_ID_ENTITIES_REF_DATAS
            ;
        end ;
        if(bemrd_transactionStarted <> 0 ) Then
            -- pour dev / debug
#             rollback ;
            commit;
            Set bemrd_transactionStarted = 0;
        End if;

        Drop Temporary table if exists TMP_ENTTCP_REFDATAS_SRC;

    end ;
End //
Delimiter ;