DELIMITER $$
USE `db_sp`$$
DROP FUNCTION IF EXISTS `bil`$$
CREATE DEFINER=`root`@`localhost` FUNCTION `bil`(num INT) RETURNS VARCHAR(7) CHARSET latin1
BEGIN
DECLARE result VARCHAR(7);
CASE num
WHEN num > 0 THEN
SET result = "Positive";
WHEN num < 0 THEN
SET result = "Negative";
ELSE SET result = "Neutral";
END CASE;
RETURN result;
END$$
DELIMITER ;
when I run SELECT bil(4); the result was Neutral. I think it should’ve been Positive. Did I miss something?
2
Answers
You can also do it by moving the
set
outside thecase
statement :the
CASE
statement has two alternative syntaxes, and you’re mixing both:It is not wrong per-se, it just renders incorrect results for your use case because you’re comparing
num
withnum > 0
(which equals1
when num is 4) and withnum < 0
(which equals0
). None match, so you get to theELSE
clause.Get rid of the extraneous
num
on top:Additionally, you need
VARCHAR(8)
rather thanVARCHAR(7)
.Demo
On a side note,
latin1
is a legacy encoding you should try to avoid in 2023. Switch toutf8mb4
whenever possible. And MySQL is one of the few database engines that accept double quotes for strings, which the SQL standard reserves for identifiers—I’d suggest you get used to single quotes to avoid surprises when working with other systems.