Search code examples
mysqlcursormysql-error-1064

Cursor definition gives error 1064, but the base select works ok. Where's the error?


I wrote the following code - which is part of a bigger stored procedure.

DROP PROCEDURE IF EXISTS CGF;
CREATE PROCEDURE CGF( target_id INT )
BEGIN
  DECLARE atual INT;
  Declare  prior INT;
  DECLARE perc_dif DECIMAL(18,2);
  DECLARE dumpdate DATETIME;
  DECLARE done SMALLINT;


  DROP TEMPORARY TABLE IF EXISTS tbl_Result;

  CREATE TEMPORARY TABLE tbl_Result 
  (
    load_date DATETIME,
    likes_fans INT,
    perc_dif DECIMAL(18,2)
  );

  DECLARE csr_alvo CURSOR FOR 
    SELECT 
      th.likes,
      th.dump_date
    FROM 
      target_history th
      INNER JOIN 
        (
        SELECT 
          max(th.dump_date) AS dump_date
        FROM 
          target_history thi
        WHERE 
          th.target_id = thi.target_id
        GROUP BY (CAST(dump_date AS DATE))
        )  t
        ON th.dump_date = t.dump_date;
END;     

If I comment the DECLARE CURSOR part, the procedure is compiled ok and created. The SELECT used, when executed outside the declaration, works with no problems.

What I'm doing wrong? Based on what I can get from internet, the syntax appears to be correct.


Solution

  • You can only DECLARE after a BEGIN. You can either move yours up to the top next to your other declares, or wrap it with a BEGIN ... END; block.