Delimiter //
/**
 * moves all data from one entity to another
 *
 * @author Armen
 */
Drop Procedure if Exists BUSINESS_ENTITIES_MOVE_ALL_DATA//

Create Procedure BUSINESS_ENTITIES_MOVE_ALL_DATA(
    In srcEntityId Int Unsigned
    , In tarEntityId Int Unsigned
    , in cleanSrcEntityData SmallInt
)
Begin
    bemad_Main: begin
        Declare bemad_transactionStarted int default 0 ;
        DECLARE Exit HANDLER FOR SQLEXCEPTION
            Begin
                if bemad_transactionStarted  <> 0 then
                    rollback;
                    set bemad_transactionStarted  = 0;
                End if;
                resignal;
            end ;

        Start Transaction;
        Set bemad_transactionStarted  = 1;
        Set @bemad_srcEntityId = srcEntityId;
        Set @bemad_tarEntityId = tarEntityId;

        savepoint bemad_paramscopy;
            savepoint bemad_acccateccpy;
                call BUSINESS_ENTITIES_COPY_ACC_CATEG(@bemad_srcEntityId, @bemad_tarEntityId, 1);
            release savepoint bemad_acccateccpy;

            savepoint bemad_reclaimccpy;
                call BUSINESS_ENTITIES_COPY_RECLAIMS(@bemad_srcEntityId, @bemad_tarEntityId, 1);
            release savepoint bemad_reclaimccpy;

            savepoint bemad_reclaimstccpy;
                call BUSINESS_ENTITIES_COPY_RECLAIMS_STATUS(@bemad_srcEntityId, @bemad_tarEntityId, 1);
            release savepoint bemad_reclaimstccpy;

            savepoint bemad_agncycpy;
                call BUSINESS_ENTITIES_COPY_AGENCIES(@bemad_srcEntityId, @bemad_tarEntityId, 1);
            release savepoint bemad_agncycpy;

            savepoint bemad_refdtcpy;
                call BUSINESS_ENTITIES_COPY_REF_DATA(@bemad_srcEntityId, @bemad_tarEntityId, 1);
            release savepoint bemad_refdtcpy;

        release savepoint bemad_paramscopy;

        savepoint bemad_datamove;
            call BUSINESS_ENTITIES_MOVE_REF_DATA(@bemad_srcEntityId, @bemad_tarEntityId, 1);
            call BUSINESS_ENTITIES_MOVE_RECLAIMS(@bemad_srcEntityId, @bemad_tarEntityId, 1);
            call BUSINESS_ENTITIES_MOVE_ACCOUNTS(@bemad_srcEntityId, @bemad_tarEntityId, 1);
        release savepoint bemad_datamove;

        savepoint bemad_dataclean;
            if(coalesce(cleanSrcEntityData, 0)<> 0) Then
            -- ici le second parametre est bien à 0 et non 1 comme pour les autres
                call BUSINESS_COPY_REF_DATA(@bemad_srcEntityId, 0);
            end if;
        release savepoint bemad_dataclean;

#         rollback; -- pour dev et mise au point
        commit;
        set bemad_transactionStarted  = 0;
    end ;
End //
Delimiter ;