简体   繁体   中英

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.

Below is a sample custom function which am trying to achieve. When I execute this script, it throws SQL error on set statement. 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 -

  1. There should be no input parameter in the function if you want the max salary from the employee table.
  2. SET must be replaced with an INTO clause.

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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