Search code examples
mysqlsqlsql-null

SELECT MAX(...) incorrectly returns NULL in stored procedure


I have a table, ga_sum_1, with a column, created_timestamp in it. When I execute the following query from the mysql command line:

mysql> select max(created_timestamp) from ga_sum_1;
+------------------------+
| max(created_timestamp) |
+------------------------+
| 2017-11-05 00:59:55    |
+------------------------+
1 row in set (0.00 sec)

And if I do the same from a very simple stored procedure:

delimiter //
create procedure test()
begin
  select max(created_timestamp) from ga_sum_1;
end//
delimiter ;

mysql> call test();
+------------------------+
| max(created_timestamp) |
+------------------------+
| 2017-11-05 00:59:55    |
+------------------------+
1 row in set (0.00 sec)

But, when I so the same from within a stored procedure:

drop procedure if exists test;

delimiter //

create procedure test()
begin
  declare cursor_end condition for sqlstate '02000';
  declare finished int default 0;
  declare game_id int(11);
  declare user_id int(11);
  declare game_instance_id bigint(20);
  declare currency varchar(15);
  declare created_timestamp timestamp;
  declare wager decimal(18,2);
  declare win decimal(18,2);
  -- cursor
  declare game_action_csr cursor for select * from game_action_view;
  declare continue handler for cursor_end set finished=1;

  -- create view dynamically
select max(created_timestamp) from ga_sum_1;

end//

delimiter ;

mysql> call test();
+------------------------+
| max(created_timestamp) |
+------------------------+
| NULL                   |
+------------------------+
1 row in set (0.00 sec)

Query OK, 0 rows affected (0.00 sec)

What am I doing wrong in the last example?

====EDIT====

Some further research shows that it is the declare created_timestamp - apparently that confuses the select on the column of the same name!


Solution

  • That's probably because of this line:

      declare created_timestamp timestamp;