Delimiter //
/**
 * If the currency code is provided, and is in application, set currency id
 * 
 * @param int batchnum
 * @author Benoit
 * @ticket #3895
 */ 
Drop Procedure if Exists LOADER_ACCOUNTS_NORMALIZE_MAP_CURRENCY_PROVIDED//
 
Create Procedure LOADER_ACCOUNTS_NORMALIZE_MAP_CURRENCY_PROVIDED (
    In batchnum int
 )
Begin

    Set @idAdminParams = GET_LOADER_INFO('ID_ADMIN_PARAMS', batchnum);

    Set @idDefaultCurrency = (Select P.DF_CURRENCIES_ID_DF_CURRENCIES 
                              From ADMIN_PARAMS P 
                              Where P.ID_ADMIN_PARAMS = @idAdminParams);
 
    UPDATE
        LOADER_ACCOUNTS A
        INNER JOIN LOADER_STATUS S
            ON S.ID_LOADER_STATUS = A.LOADER_STATUS_ID_LOADER_STATUS
        LEFT JOIN DF_CURRENCIES C
            ON C.DF_CURRENCIES_CODE = A.DF_CURRENCIES_CODE
    SET
        A.DF_CURRENCIES_ID_DF_CURRENCIES = 
            (CASE WHEN C.ID_DF_CURRENCIES IS NOT NULL
                THEN C.ID_DF_CURRENCIES
                ELSE @idDefaultCurrency
            END)
        , S.LOADER_STATUS_ERRCOUNT = 
            (CASE WHEN C.ID_DF_CURRENCIES IS NULL
                THEN S.LOADER_STATUS_ERRCOUNT + 1
                ELSE S.LOADER_STATUS_ERRCOUNT
            END)
        , S.LOADER_STATUS_ERRMSGS = 
            (CASE WHEN C.ID_DF_CURRENCIES IS NULL
                THEN LOADER_CONCAT_ERR(S.LOADER_STATUS_ERRMSGS, Concat('Code monaie inexistant :', A.DF_CURRENCIES_CODE ) )
                ELSE S.LOADER_STATUS_ERRMSGS
            END)
    WHERE 
        Coalesce(A.DF_CURRENCIES_CODE, '') != ''
        AND S.LOADER_STATUS_BATCH_NUM = batchnum
    ;
    
End //
Delimiter ;