Mysql 函数从查询中返回一个值

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/4940036/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-31 18:40:36  来源:igfitidea点击:

Mysql function returning a value from a query

mysqlfunctionmysql-error-1064

提问by Cesar

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 语法错误。

SQL Error (1064): You have an error in your SQL syntax;

SQL 错误 (1064):您的 SQL 语法有错误;

回答by theChrisKent

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.).

假设这些都是通用名称(表不会是一个好的表名),问题是你不能使用 == 进行比较。您还缺少一些关键语法(DECLARE、SELECT INTO 等)。

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

MySQL 比较函数和运算符

Related Question: Single Equals in MYSQL

相关问题:MYSQL 中的单等号

Function Help: http://www.databasejournal.com/features/mysql/article.php/3569846/MySQL-Stored-Functions.htm

函数帮助:http: //www.databasejournal.com/features/mysql/article.php/3569846/MySQL-Stored-Functions.htm