Problema com Procedure em MySQL

13 respostas
T

Pessoal,

vamo ver se podem me ajudar. To tentando criar uma procedure pra buscar a quantidade de vezes que um número ocorreu na coluna1, coluna2. Depois será somado a quantidade de ocorrencias da coluna1 com a coluna2. Depois de ter esse resultado, faria um insert em outra tabela, com o número em questão e o resultado da soma dita anteriormente. O problema que ta dando erro de sintaxe. Não sei se estou declarando de uma forma errada…segue o código:

DELIMITER &&
CREATE PROCEDURE quantidadeSorteados_proc ()
    DECLARE B1 INTEGER;
    DECLARE B2 INTEGER;
    DECLARE RESULT INTEGER;
    DECLARE PARAM INT DEFAULT 1;

  BEGIN

  WHILE PARAM <= 25 DO
    RESULT = 0;
    SELECT COUNT(col1) INTO B1 from sorteio where col1 = PARAM;
    SELECT COUNT(col2) INTO B2 from sorteio where col2 = PARAM;
    RESULT = B1 + B2;
    INSERT INTO tb_quantidade_saidas VALUES (PARAM, RESULT);
  END WHILE;

  END &&
DELIMITER;

Desde já agradeço a ajuda.

13 Respostas

G

tiagofla:
Pessoal,

vamo ver se podem me ajudar. To tentando criar uma procedure pra buscar a quantidade de vezes que um número ocorreu na coluna1, coluna2. Depois será somado a quantidade de ocorrencias da coluna1 com a coluna2. Depois de ter esse resultado, faria um insert em outra tabela, com o número em questão e o resultado da soma dita anteriormente. O problema que ta dando erro de sintaxe. Não sei se estou declarando de uma forma errada…segue o código:

DELIMITER &&
CREATE PROCEDURE quantidadeSorteados_proc ()
    DECLARE B1 INTEGER;
    DECLARE B2 INTEGER;
    DECLARE RESULT INTEGER;
    DECLARE PARAM INT DEFAULT 1;

  BEGIN

  WHILE PARAM <= 25 DO
    RESULT = 0;
    SELECT COUNT(col1) INTO B1 from sorteio where col1 = PARAM;
    SELECT COUNT(col2) INTO B2 from sorteio where col2 = PARAM;
    RESULT = B1 + B2;
    INSERT INTO tb_quantidade_saidas VALUES (PARAM, RESULT);
  END WHILE;

  END &&
DELIMITER;

Desde já agradeço a ajuda.

Posta o erro

T

Ok. Logo mais a noite postarei o erro, pois estou sem meu notebook aqui no trabalho…farei um novo teste e continuando o erro, postarei o mesmo.

T

Desculpem a demora pois tive alguns problemas…minha procedure está assim:

DELIMITER $$

DROP PROCEDURE IF EXISTS `schema`.`quantSorteados` $$
CREATE PROCEDURE `schema`.`quantSorteados` ()
BEGIN
DECLARE B1 INT;
DECLARE B2 INT;
DECLARE RESULT INT;
DECLARE i INT = 1;

  WHILE i <= 25 DO
    RESULT = 0
    SELECT COUNT(bola1) INTO B1 from sorteio where bola1 = i;
    SELECT COUNT(bola2) INTO B2 from sorteio where bola2 = i;
    RESULT = B1 + B2;
    INSERT INTO tb_quantidade_saidas VALUES (PARAM, RESULT);
  END WHILE;
END $$

DELIMITER ;

Rodei e ta dando o seguinte erro:

Script line: 4	You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near '= 1;

  WHILE i <= 25 DO
    RESULT = 0
    SELECT COUNT(bola1) INTO B1 from' at line 6

Quem ja passou por isso e puder ajudar, agradeço.

G

Tente adicionar o ‘schema’ no from

T

Coloquei o schema mas o problema persiste.

D

1 -

RESULT = 0

Result é uma palavra reservada do MySQL.
Além de que, para setar uma variável com um valor, utilize o set.

Outra coisa, eu preferiria utilizar CURSOR para realizar os counts.

Tenta assim e ve se dá algum erro (não testei, fiz no notepad++, de cabeça)

DELIMITER $$  
  
DROP PROCEDURE IF EXISTS `schema`.`quantSorteados` $$  
CREATE PROCEDURE `schema`.`quantSorteados` ()  
BEGIN  
DECLARE B1 INT;  
DECLARE B2 INT;  
DECLARE resultado INT;  
DECLARE i INT = 1;  

DECLARE cursorCount1 CURSOR FOR
SELECT COUNT(bola1) AS count1 from sorteio where bola1 = i; 

DECLARE cursorCount2 CURSOR FOR
    SELECT COUNT(bola2) AS count2 from sorteio where bola2 = i;
  
  WHILE i <= 25 DO  
    SET resultado = 0;
    
	OPEN cursorCount1;
	FETCH cursorCount1 INTO B1;
	CLOSE cursorCount1;
	
	OPEN cursorCount2;
	FETCH cursorCount2 INTO B2;
	CLOSE cursorCount2;

    SET resultado = B1 + B2;  
    INSERT INTO tb_quantidade_saidas VALUES (PARAM, resultado);  
  END WHILE;  
END $$  
  
DELIMITER ;
T

Testei o código acima e deu o seguinte erro:

Script line: 4	You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near '= 1;    
  
DECLARE cursorCount1 CURSOR FOR  
SELECT COUNT(bola1) AS count1 f' at line 6
D

O problema passou batido, SQL não é Java, onde se declara e atribui valor.

//isso está errado
DECLARE i INT = 1;
//troque por
DECLARE i INT;
SET i = 1;
T

Sei…eu tinha corrigido essa parada mas não deu certo…

Fui debugando o procedure usando o botão step do MySQL Query Browser, e percebi que o erro está ocorrendo nesta linha:

Será que a sintaxe está errada?

D

tiagofla:
Sei…eu tinha corrigido essa parada mas não deu certo…

Fui debugando o procedure usando o botão step do MySQL Query Browser, e percebi que o erro está ocorrendo nesta linha:

Será que a sintaxe está errada?


O nome da tabela é schema?

T

não. Coloquei isso pra simbolizar o schema do banco.

schema.nome_da_procedure

T

Vou criar o mesmo banco e a procedure no Oracle. Nunca tinha criado no MySQL…

T

Continuei a fazer uns testes aqui e consegui acertar a procedure. Segue a solução:

CREATE DEFINER=`root`@`localhost` PROCEDURE `vezesSorteado`()
BEGIN
DECLARE r INT;
DECLARE i INT;
DECLARE bol1 INT;
DECLARE bol2 INT;
DECLARE b1 INT;
DECLARE b2 INT;
SET i = 1;

        WHILE i <= 25 do
          select count(bola1) into b1 from sorteio where bola1 = i;
          SET bol1 = b1;
          select count(bola2) into b2 from sorteio where bola2 = i;
          SET bol2 = b2;

          SET r = bol1 + bol2;
          INSERT INTO tb_quantidade_saidas VALUES (i, r);
          SET i = i + 1;
          SET r = 0;

        END WHILE;
END
Criado 16 de março de 2012
Ultima resposta 17 de mar. de 2012
Respostas 13
Participantes 3