Delimiter //
/**

**/

drop function if exists CASH_BUSINESS_GET_ENTRIES_ID_MATCHING_CODE //

Create Function CASH_BUSINESS_GET_ENTRIES_ID_MATCHING_CODE(
		accounts_ref varchar(40)
		, entries_acc_ext_ref varchar(45)
		, id_entities Int unsigned
	)
	returns Varchar(60)
Begin
	return (
			Select 
				ENT.DF_MATCH_STAT_ID_DF_MATCH_STAT
			From ENTRIES ENT
				Inner Join ENTRIES_has_ACCOUNTS EHA
					on ENT.ID_ENTRIES = EHA.ENTRIES_ID_ENTRIES
                    AND ENTRIES_PERMANENT_ATTACHEMENT = 1
				Inner join ACCOUNTS ACC
					On ACC.ID_ACCOUNTS = EHA.ACCOUNTS_ID_ACCOUNTS
			Where
				ACC.ACCOUNTS_REF = accounts_ref
				And EHA.ENTRIES_ACC_EXT_REF = entries_acc_ext_ref
				And ACC.ENTITIES_ID_ENTITIES = id_entities
			Limit 1
		)
	;
End //
Delimiter ;