Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Mysql function returning a value from a query

Tags:

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;

like image 612
Cesar Avatar asked Feb 09 '11 00:02

Cesar


People also ask

How do you return a value in MySQL?

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.

How do I return a select statement from a function in MySQL?

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.

What can a MySQL function return?

The function can return string, integer, char etc. To return table from MySQL, use stored procedure, not function.

Can MySQL function return multiple values?

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.


1 Answers

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

like image 151
theChrisKent Avatar answered Oct 13 '22 13:10

theChrisKent