MySQL create function for range of values with equivalent numbers
What is wrong with this function. Here is my expected output is
1 = 10
2 to 3 = 7
4 to 10 = 开发者_开发知识库5
11 to 30 = 2
31 to 100 = 1
DELIMITER $$
DROP FUNCTION IF EXISTS `computeScore`$$
CREATE DEFINER=`root`@`localhost` FUNCTION `computeScore`(`POS` INT(11)) RETURNS int(11)
READS SQL DATA
DETERMINISTIC
BEGIN
DECLARE ordinal INT;
SELECT (
CASE
WHEN POS < 2 THEN 10
WHEN POS >= 2 < 4 THEN 7
WHEN POS >= 4 < 11 THEN 5
WHEN POS >= 11 < 31 THEN 2
ELSE 1
END )
INTO ordinal;
RETURN ordinal;
RETURN 0;
END;
$$
DELIMITER ;
Output: I always get 10
Try this:
SELECT (
CASE
WHEN POS < 2 THEN 10
WHEN POS >= 2 && POS < 4 THEN 7
WHEN POS >= 4 && POS < 11 THEN 5
WHEN POS >= 11 && POS < 31 THEN 2
ELSE 1
END )
The CASE
part should be
CASE
WHEN POS < 2 THEN 10
WHEN POS >= 2 AND POS < 4 THEN 7
WHEN POS >= 4 AND POS < 11 THEN 5
WHEN POS >= 11 AND POS < 31 THEN 2
ELSE 1
END
What is wrong?
From the reference about SELECT..INTO statament - This SELECT syntax stores selected columns directly into variables. Therefore, only a single row may be retrieved.
Check that query returns one record.
EDIT:
The code can be like this -
SET ordinal = CASE
WHEN pos < 2 THEN 10
WHEN pos >= 2 AND pos < 4 THEN 7
WHEN pos >= 4 AND pos < 11 THEN 5
WHEN pos >= 11 AND pos < 31 THEN 2
ELSE 1
END;
精彩评论