Mysql function returning a value from a query

∥☆過路亽.° 提交于 2019-11-27 17:41:45

问题


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;


回答1:


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



来源:https://stackoverflow.com/questions/4940036/mysql-function-returning-a-value-from-a-query

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!