Hello,
We are trying to create a simple function to handle currency conversion. We have a table that stores the currency conversion rates and all I wanted to do is a scalar function that takes the two currency codes and the amount and returns the converted amount like convert_currency(‘USD’, ‘EUR’, 10) and it would return the amount in EUR.
I tried using UDFs but apparently they cannot contain select statements and are meant purely for computational stuff. Since I only need the conversion rate I also tried using the scalar function with the select string as parameter to get the rate. It then creates the UDF but errors when calling it. Can anyone think of a solution?
If I mark the return type as TABLE and use a TVF it works but it is not exactly what I want to do, I need to return a scalar to use inline on the selects where I need currency conversion:
DELIMITER //
CREATE FUNCTION convert_currency(currencyFrom VARCHAR(3), currencyTo VARCHAR(3), amount DECIMAL(18,8))
RETURNS TABLE AS RETURN
SELECT ConversionRate * amount as convertedAmount
FROM ConversionRates
WHERE SourceCurrency = currencyFrom
AND TargetCurrency = currencyTo
LIMIT 1;
//
DELIMITER ;
The picture shows what I want to achieve but done in postgress: