Delimiter //
/**
 * Author:  armen
 * Created: 2 déc. 2019
 */

Drop Procedure if exists LOADER_ACCOUNTS_PENALTIES_INSERT//
Create Procedure LOADER_ACCOUNTS_PENALTIES_INSERT (
    In batchnum int 
    , In lastId Int
)
Begin 
    set @lapi_batchnum = batchnum;
    set @lapi_lastId = lastId;

    -- 44116
    Insert into ACCOUNTS_has_DF_PENALTIES_RULES (
        ACCOUNTS_ID_ACCOUNTS
        , DF_PENALTIES_RULES_ID_DF_PENALTIES_RULES
    )
    Select 
        Case When la.ID_ACCOUNTS Is null Then 
                la.ID_ACCOUNTS_NEW +@lapi_lastId 
            Else la.ID_ACCOUNTS  
        End ACCOUNTS_ID_ACCOUNTS
        , la.ID_DF_PENALTIES_RULES_CODE_FR4416
    From LOADER_STATUS ls
        Inner Join LOADER_ACCOUNTS la
            On ls.ID_LOADER_STATUS = la.ID_LOADER_ACCOUNTS
    Where
        ls.LOADER_STATUS_ERRCOUNT = 0
        and ls.LOADER_STATUS_BATCH_NUM = @lapi_batchnum
        And la.ID_DF_PENALTIES_RULES_CODE_FR4416 is not null
    ;

    -- clause penal
    Insert into ACCOUNTS_has_DF_PENALTIES_RULES (
        ACCOUNTS_ID_ACCOUNTS
        , DF_PENALTIES_RULES_ID_DF_PENALTIES_RULES
    )
    Select 
        Case When la.ID_ACCOUNTS Is null Then 
                la.ID_ACCOUNTS_NEW +@lapi_lastId 
            Else la.ID_ACCOUNTS  
        End ACCOUNTS_ID_ACCOUNTS
        , la.ID_DF_PENALTIES_RULES_CODE_FRLTPNCSE
    From LOADER_STATUS ls
        Inner Join LOADER_ACCOUNTS la
            On ls.ID_LOADER_STATUS = la.ID_LOADER_ACCOUNTS
    Where
        ls.LOADER_STATUS_ERRCOUNT = 0
        and ls.LOADER_STATUS_BATCH_NUM = @lapi_batchnum
        And la.ID_DF_PENALTIES_RULES_CODE_FRLTPNCSE is not null
    ;
End //

Delimiter ;
