Delimiter //
/**
 * Calculates the entry balance (ENT_DEBIT - ENT_CREDIT)
 * 
 * @author Benoit
 * @ticket #4135
 */
Drop Procedure If Exists LOADER_ENTRIES_MAP_CALCULATE_BALANCE//
Create Procedure LOADER_ENTRIES_MAP_CALCULATE_BALANCE(
    In batchnum Int
)
Begin
    
    Update
        LOADER_ENTRIES E
        Inner Join LOADER_STATUS S
            On S.ID_LOADER_STATUS = E.LOADER_STATUS_ID_LOADER_STATUS
    Set
        E.ENTRIES_ENT_BALANCE = Coalesce(E.ENT_BALANCE
									, Coalesce(E.ENTRIES_ENT_DEBIT, 0) - Coalesce(E.ENTRIES_ENT_CREDIT, 0)
								)
    Where
        S.LOADER_STATUS_BATCH_NUM = batchnum
		And E.ENTRIES_ENT_BALANCE Is Null
    ;

End//
Delimiter ;