我正在尝试创建一个存储过程来获取表中的中位年龄,但收到未声明的变量错误。我的代码是:
DELIMITER //
CREATE PROCEDURE MedianAge()
BEGIN
SET @row_count = (SELECT COUNT(*) FROM employee);
SET @median_index = (@row_count/2);
SELECT TIMESTAMPDIFF(YEAR, bdate, CURDATE()) AS age
FROM employee ORDER BY bdate DESC
LIMIT median_index, median_index;
END //
DELIMITER ;
我收到错误:
Error Code: 1327. Undeclared variable: median_index
据我所知,我已经正确声明了变量,并且不确定为什么 SELECT 语句不起作用。
您正在使用用户定义的变量(前缀为 @(。但是,在存储过程中,应使用局部变量(不带前缀(。这些变量必须在使用前声明。这里很好地解释了差异。
你会得到这样的东西:
DELIMITER //
CREATE PROCEDURE MedianAge()
BEGIN
DECLARE row_cnt INT unsigned;
DECLARE median_index INT unsigned;
SET row_cnt = (SELECT COUNT(*) FROM employees);
SET median_index = (row_cnt/2);
SELECT TIMESTAMPDIFF(YEAR, bdate, CURDATE()) AS age
FROM employee ORDER BY bdate DESC
LIMIT median_index, median_index;
END //
DELIMITER ;
另外,请记住,row_count是MySQL中的保留字(函数名称(。最好避免将其用作变量名。