SQL中值未声明的变量

时间:2018-08-10 14:10:02

标签: mysql sql

我试图创建一个存储过程来获取表中的年龄中位数,但是却出现了一个未声明的变量错误。我的代码是:

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语句不起作用。

1 个答案:

答案 0 :(得分:3)

您正在使用用户定义的变量(以@开头)。但是,在存储过程中,应使用局部变量(无前缀)。这些变量必须在使用前声明。差异已得到很好的解释here

您会得到这样的东西:

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(函数名)中的保留字。最好避免将其用作变量名。