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

Create Procedure LOADER_MEMBERSACCRED_ENTITIES_HAS_MBR_INSERT (
    In batchnum int
    , In lastEnttHsMbrId Int Unsigned
)
Begin
        Set @idEntities = GET_LOADER_INFO('ID_ENTITIES', batchnum);
        set @lastEnttHsMbrId = lastEnttHsMbrId;
        Insert Into ENTITIES_has_MEMBERS (
                ID_ENTITIES_has_MEMBERS
                , ENTITIES_ID_ENTITIES, MEMBERS_ID_MEMBERS
                , DF_ACCESS_PROFILES_ID_DF_ACCESS_PROFILES, DF_FUNCTIONS_ID_DF_FUNCTIONS
            )
        Select
            ARD.ID_ENTITIES_has_MEMBERS_NEW + @lastEnttHsMbrId
            , @idEntities, ARD.ID_MEMBERS
            , ARD.DF_ACCESS_PROFILES_ID_DF_ACCESS_PROFILES, ARD.DF_FUNCTIONS_ID_DF_FUNCTIONS
        From
            LOADER_STATUS sts 
            Inner Join LOADER_MEMBERSACCRED ARD
                On ARD.LOADER_STATUS_ID_LOADER_STATUS = sts.ID_LOADER_STATUS
        Where
            sts.LOADER_STATUS_ERRCOUNT = 0 
            And ARD.ID_ENTITIES_has_MEMBERS_NEW Is Not Null
            And ARD.ID_ENTITIES_has_MEMBERS Is Null
            And sts.LOADER_STATUS_BATCH_NUM = batchnum
        ;
End //

Delimiter ;