Delimiter //
/**
 * Author:  armen
 * Created: 27 janv. 2020
 */

drop function if exists CASH_BUSINESS_GET_MAIN_CONTACT_REF //

Create Function CASH_BUSINESS_GET_MAIN_CONTACT_REF(
		accounts_ref varchar(40)
	)
	returns Varchar(40)
Begin
	return Coalesce(
            (
                Select 
                    ctc.CONTACTS_REF
                From ACCOUNTS acc
                    Inner Join CONTACTS ctc
                        on acc.CONTACTS_ID_CONTACTS = ctc.ID_CONTACTS
                Where
                        acc.ACCOUNTS_REF = accounts_ref
                Limit 1
            )
            , accounts_ref
		)
	;
End //
Delimiter ;
