1

I am trying to create a stored procedure to obtain the median age within a table but am getting an undeclared variable error. My code is:

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 ;

I am receiving the error:

Error Code: 1327. Undeclared variable: median_index

As far as I am aware I have declared the variable correctly and am unsure why the SELECT statement does not work.

JackDG
  • 49
  • 1
  • 8

1 Answers1

3

You are using user-defined variables (prefixed with @). However, within the stored procedures you should use local variables (with no prefix). These variables have to be declared prior to use. The difference is well explained here.

You would get something like this:

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 ;

Also, keep in mind that row_count is a reserved word in MySQL (a function name). It's better to avoid using it as a variable name.

Ildar Akhmetov
  • 1,331
  • 13
  • 22