Delimiter //
/**
 * Author:  armen
 * Created: 31 janv. 2018
 */
Drop Procedure if exists LOADER_MEMBERSACCRED_NORMALIZE_MAP_ACCRED_NEW_RULES//

Create Procedure LOADER_MEMBERSACCRED_NORMALIZE_MAP_ACCRED_NEW_RULES (
    In batchnum int
)
Begin
--     Set @idEntities = GET_LOADER_INFO('ID_ENTITIES', batchnum);
    Drop Temporary Table IF EXISTS TMP_LOADER_MEMVERACCRED_NEW;
    Create Temporary Table TMP_LOADER_MEMVERACCRED_NEW (
                ID_TMP_LOADER_MEMVERACCRED_NEW Int Unsigned Not Null Primary Key Auto_increment
                , LOADER_MEMBERSACCRED_ID_LOADER_MEMBERSACCRED Int Unsigned Not Null 
                , Index IX_TMP_LOADER_MEMVERACCRED_NEW_1 (LOADER_MEMBERSACCRED_ID_LOADER_MEMBERSACCRED )
            )
        ;
    Insert Into TMP_LOADER_MEMVERACCRED_NEW (
            LOADER_MEMBERSACCRED_ID_LOADER_MEMBERSACCRED
        )
    Select
        src.ID_LOADER_MEMBERSACCRED
    From LOADER_STATUS sts
        Inner Join LOADER_MEMBERSACCRED src
            On sts.ID_LOADER_STATUS = src.LOADER_STATUS_ID_LOADER_STATUS
    Where
        src.ID_ENTITIES_has_MEMBERS Is Null
        And src.ID_ENTITIES_has_MEMBERS_NEW Is Null
        And sts.LOADER_STATUS_ERRCOUNT = 0
        And sts.LOADER_STATUS_BATCH_NUM = batchnum
    ;

    Update
        LOADER_MEMBERSACCRED src
        Inner Join TMP_LOADER_MEMVERACCRED_NEW tmpnew
            On src.ID_LOADER_MEMBERSACCRED = tmpnew.LOADER_MEMBERSACCRED_ID_LOADER_MEMBERSACCRED

    Set 
        src.ID_ENTITIES_has_MEMBERS_NEW = tmpnew.ID_TMP_LOADER_MEMVERACCRED_NEW
    ;
    
    Drop Temporary Table IF EXISTS TMP_LOADER_MEMVERACCRED_NEW;

End //
Delimiter ;