سؤال

I have a table 'dia'

table: dia

and I have the function:

 create table log(
      cont int
 );

 delimiter //
 CREATE FUNCTION teste (calendario INT, data_selecionada DATE)
      RETURNS INT
 BEGIN

 DECLARE corrente INT DEFAULT 0;
 DECLARE data_inicio DATE DEFAULT NULL;
 DECLARE inicio INT DEFAULT 0;
 DECLARE maior_corrente INT DEFAULT 0;
 DECLARE existe_mais_linhas INT DEFAULT 0;
 DECLARE dia_atual DATE;
 DECLARE dia_anterior DATE DEFAULT NULL;
 DECLARE semana_atual INT DEFAULT -1;
 DECLARE semana_anterior INT DEFAULT -1;
 DECLARE total_vidas INT DEFAULT 0;
 DECLARE vidas INT DEFAULT 0;

 DECLARE meuCursor CURSOR FOR SELECT data, YEARWEEK(data), inicio_corrente FROM dia WHERE data >= data_selecionada and tem_corrente = 1 and calendario_id = calendario order by data asc;

 DECLARE CONTINUE HANDLER FOR NOT FOUND SET existe_mais_linhas=1;

 SELECT data into data_inicio FROM dia WHERE tem_corrente = 1 and inicio_corrente = 1 and data < data_selecionada order by data desc limit 1;

 OPEN meuCursor;

 meuLoop: LOOP
 FETCH meuCursor INTO dia_atual, semana_atual, inicio;
      insert into log (cont) values (1);

      IF existe_mais_linhas = 1 THEN
           LEAVE meuLoop;
      END IF;

 END LOOP meuLoop;

 CLOSE meuCursor;
 RETURN 0;

 END//
 delimiter ;

when I call the function:

 SELECT teste( 1,  '2014-01-26' )

the table log contains only one row... it's wrong, because the cursor have to visit all the nine rows... but, if i delete the line:

 SELECT data into data_inicio FROM dia WHERE tem_corrente = 1 and inicio_corrente = 1 and data < data_selecionada order by data desc limit 1;"

(The line is irrelevant, I think). But now, When I call the same function, the table log contains nine rows... how that line influences the loop??

هل كانت مفيدة؟

المحلول

The first query returned NO data.. so the variable is already SET and the program flow continued.. and since you refer it inside a loop before unsetting it.. instead of checking on no data for a cursor as you expected.!!

 SELECT data into data_inicio FROM dia WHERE tem_corrente = 1 and inicio_corrente = 1 and data < data_selecionada order by data desc limit 1;


 IF existe_mais_linhas = 1 THEN
    SET existe_mais_linhas = 0;-- unset it using SET..
  END IF;

 OPEN meuCursor;

 meuLoop: LOOP
 FETCH meuCursor INTO dia_atual, semana_atual, inicio;

      IF existe_mais_linhas = 1 THEN
           LEAVE meuLoop;
      END IF;

       -- Move the insert after checking it!

      insert into log (cont) values (1);

 END LOOP meuLoop;
مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top