Delimiter //
/**
 * If dates are given, keep them, else, set to current date.
 * 
 * @param int batchnum
 * @author Benoit
 * @ticket #3900
 */ 
Drop Procedure if Exists LOADER_ACCOUNTS_NORMALIZE_MAP_DATES_PROVIDED_OR_NOT//
 
Create Procedure LOADER_ACCOUNTS_NORMALIZE_MAP_DATES_PROVIDED_OR_NOT (
    In batchnum int
)
Begin

    -- For new accounts
    Update 
        LOADER_ACCOUNTS A
        Inner Join LOADER_STATUS S
            On S.ID_LOADER_STATUS = A.LOADER_STATUS_ID_LOADER_STATUS
    Set 
        A.ACCOUNTS_CREATED =
            (Case When Char_Length(Coalesce(A.ACCOUNTS_CREATED, '')) != 0       -- ni null ni vide
                Then A.ACCOUNTS_CREATED
                Else Now()
            End)
        , A.ACCOUNTS_LAST_EVENT_UPDATE =
            (Case When Char_Length(Coalesce(A.ACCOUNTS_LAST_EVENT_UPDATE, '')) != 0
                Then A.ACCOUNTS_LAST_EVENT_UPDATE
                Else Now()
            End)
    Where
        S.LOADER_STATUS_BATCH_NUM = batchnum
        And A.ID_ACCOUNTS_NEW Is Not Null
    ;

    -- For existing accounts
    -- @todo : not very usefull while there is no date format validation
    Update 
        LOADER_ACCOUNTS LA
        Inner Join LOADER_STATUS S
            On S.ID_LOADER_STATUS = LA.LOADER_STATUS_ID_LOADER_STATUS
        Inner Join ACCOUNTS A
            On A.ID_ACCOUNTS = LA.ID_ACCOUNTS
    Set 
        LA.ACCOUNTS_CREATED =
            (Case When Char_Length(Coalesce(LA.ACCOUNTS_CREATED, '')) != 0      -- ni null ni vide
                Then LA.ACCOUNTS_CREATED
                Else A.ACCOUNTS_CREATED
            End)
        , LA.ACCOUNTS_LAST_EVENT_UPDATE =
            (Case When Char_Length(Coalesce(LA.ACCOUNTS_LAST_EVENT_UPDATE, '')) != 0
                Then LA.ACCOUNTS_LAST_EVENT_UPDATE
                Else A.ACCOUNTS_LAST_EVENT_UPDATE
            End)
    Where
        S.LOADER_STATUS_BATCH_NUM = batchnum
    ;

End //
Delimiter ;