简体   繁体   English

如何将 select 语句中的聚合值设置为 MySQL 自定义 function 中的变量

[英]How can I set an aggregate value from a select statement to a variable inside MySQL custom function

I am trying to create a custom function using the SELECT query result in MySQL.我正在尝试使用 MySQL 中的 SELECT 查询结果创建自定义 function。

Below is a sample custom function which am trying to achieve.下面是一个正在尝试实现的示例自定义 function。 When I execute this script, it throws SQL error on set statement.当我执行此脚本时,它会在 set 语句上抛出 SQL 错误。 Please advise how this can be done.请告知如何做到这一点。

My attempt is below:我的尝试如下:

DELIMITER //
CREATE FUNCTION get_max(
    salary INT
)
RETURNS INT

BEGIN
DECLARE max_salary INT;
SET max_salary = select MAX(salary) from employee; --statement to check
RETURN max_salary;
END; //
DELIMETER;

enter image description here在此处输入图像描述

There are few concerns in your function -您的 function 中几乎没有问题 -

  1. There should be no input parameter in the function if you want the max salary from the employee table.如果你想从 employee 表中获取 max salary,function 中应该没有输入参数。
  2. SET must be replaced with an INTO clause. SET 必须替换为 INTO 子句。

So, The correct syntax should be -所以,正确的语法应该是 -

DELIMITER //
CREATE FUNCTION get_max()
RETURNS INT

BEGIN
DECLARE max_salary INT;
SELECT MAX(salary) 
  INTO max_salary
  FROM employee;

RETURN max_salary;

END; 
//
DELIMETER;

Demo. 演示。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM