i want to create a function which calculates a value using a query and I am having a problem returning the value:
Shortened, my query is:
CREATE FUNCTION func01(value1 INT , monto DECIMAL (10,2)) RETURNS DECIMAL(10,2) BEGIN SET @var_name = 0; select @var_name=if(value1 = 1,monto * table.divisa_dolar,table.monto *divisa_euro) from table where data_init = 1; return @var_nam; END
I get a SQL syntax error.
SQL Error (1064): You have an error in your SQL syntax;
To return a value from stored procedure, you need to use user defined session specific variable. Add @ symbol before variable name. Now second call for difference of two values. Call the stored procedure.
MySQL stored functions only return a single scalar value. They cannot return result sets. Functions can be used in a scalar expression context. You can use a stored procedure to return a result set, but you can't use it in an expression.
The function can return string, integer, char etc. To return table from MySQL, use stored procedure, not function.
MySQL stored function returns only one value. To develop stored programs that return multiple values, you need to use stored procedures with INOUT or OUT parameters.
Assuming these are all generic names (table will not be a good table name), the problem is you can't use == for comparison. You are also missing some key syntax (DECLARE, SELECT INTO, etc.).
Change to this:
CREATE FUNCTION func01(value1 INT , monto DECIMAL (10,2)) RETURNS DECIMAL(10,2) DETERMINISTIC BEGIN DECLARE var_name DECIMAL(10,2); SET var_name = 0; SELECT if(value1 = 1,monto *divisa_dolar,monto *divisa_euro) INTO var_name FROM table WHERE data_init = 1; RETURN var_name; END
MySQL Comparison Functions and Operators
Related Question: Single Equals in MYSQL
Function Help: http://www.databasejournal.com/features/mysql/article.php/3569846/MySQL-Stored-Functions.htm
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With