DELIMITER $$ CREATE OR REPLACE DEFINER=`root`@`localhost` FUNCTION `vn`.`invoiceOutAmount`(vInvoiceRef VARCHAR(15)) RETURNS decimal(10,2) NOT DETERMINISTIC READS SQL DATA BEGIN DECLARE totalAmount DECIMAL(10,2); SELECT SUM(vat) INTO totalAmount FROM ( SELECT iot.vat FROM invoiceOutTax iot JOIN invoiceOut io ON io.id = iot.invoiceOutFk WHERE io.ref = vInvoiceRef UNION ALL SELECT ioe.amount FROM invoiceOutExpense ioe JOIN invoiceOut io ON io.id = ioe.invoiceOutFk WHERE io.ref = vInvoiceRef ) t1; RETURN totalAmount; END$$ DELIMITER ;