You can set local variables with DECLARE statement as shown below:
DELIMITER $$
CREATE FUNCTION my_func() RETURNS INT
DETERMINISTIC
BEGIN
DECLARE v1, v2 INT DEFAULT 2; -- v1 and v2 are 2.
DECLARE v3, v4 INT DEFAULT v1 + v2; -- v3 and v4 are 4.
DECLARE result INT; -- result is NULL.
SELECT v3 + v4 INTO result; -- result is 8.
RETURN result; -- 8 is returned.
END$$
DELIMITER ;
*Memos:
Then, 8
is returned as shown below:
mysql> SELECT my_func();
+-----------+
| my_func() |
+-----------+
| 8 |
+-----------+
Be careful, if DECLARE
block is not set within the top of BEGIN ... END
statement within stored programs as shown below:
DELIMITER $$
CREATE FUNCTION my_func() RETURNS INT
DETERMINISTIC
BEGIN
SELECT 2 + 3; -- Because of this
DECLARE v1, v2 INT DEFAULT 2; -- Not the top
DECLARE v3, v4 INT DEFAULT v1 + v2; -- Not the top
DECLARE result INT; -- Not the top
SELECT v3 + v4 INTO result;
RETURN result;
END$$
DELIMITER ;
Or:
DELIMITER $$
CREATE FUNCTION my_func() RETURNS INT
DETERMINISTIC
BEGIN
DECLARE v1, v2 INT DEFAULT 2;
DECLARE v3, v4 INT DEFAULT v1 + v2;
SELECT 2 + 3; -- Because of this
DECLARE result INT; -- Not the top
SELECT v3 + v4 INTO result;
RETURN result;
END$$
DELIMITER ;
Then, there is the error below:
ERROR 1064 (42000): You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near ...
:=
assignment operator, rather than the=
equality operator? – Hover