comando loop no MySQL

MySQL

25/05/2012

Olá pessoal!

Quero montar uma procedure que possa me retornar os a totalização dos valores de uma tabela da seguinte forma:

Dinheiro - 0,00
Cartão - 0,00
Cheque - 0,00

Tenho a seguinte consulta:

select cxt.caixactrl, cxt.sigla, fpg.descricao, cxt.valor from caixatotalizador01 cxt
inner join formapgto fpg on cxt.formapgto = fpg.codigo
where cxt.formapgto in (1,2,3);

Preciso fazer um loop para que eu possa acessar os registros dessa consulta para fazer as verificações e somas.
ex.:
Se formapgto = 1 então
Se sigra in (SU,VD,RB) então
Dinheiro = Dinheiro + valor;
Senão
Se sigla = SA então
Dinheiro = Dinheiro - valor;

SU - suprimento
SA - sangria
VD - venda
RB - recebimento
RE - retirada de encerramento
SF - saldo final
DF - diferenca

No FireBird faço isso tranquilo, mas preciso fazer isso no MySQL e não sei como.

Agradeço desde já qualquer ajuda...
Vagner Almeida

Vagner Almeida

Curtidas 0

Respostas

Joel Rodrigues

Joel Rodrigues

25/05/2012

Pesquise sobre como utilizar cursores no MySQL.
GOSTEI 0
Vagner Almeida

Vagner Almeida

25/05/2012

O select que eu criei retorna os seguintes valores:

caixactrl | sigla | descricao | valor
1 VD TEF 58,00
1 SU DINHEIRO 17,45
1 VD DINHEIRO 47,50

A procedure abaixo ERA para me trazer os seguintes valores:

vlrdin | vlrcar | vlrchq
64,95 58,00 0,00

mas os valores que esta retornando são:

vlrdin | vlrcar | vlrchq
112,45 58,00 0,00

O que está errado com o codigo abaixo? Como faço para me retornar o valor correto?
Agradeço qualquer ajuda...

CREATE DEFINER = root@localhost PROCEDURE `sp_totalizadorcx`(
in nrocx integer,
out vlrdin decimal(9,2),
out vlrcar decimal(9,2),
out vlrchq decimal(9,2)
)
NOT DETERMINISTIC
CONTAINS SQL
SQL SECURITY DEFINER
COMMENT
BEGIN
DECLARE done INT DEFAULT 0;
DECLARE cx integer;
DECLARE sg char(2);
DECLARE dc varchar(10);
DECLARE vl decimal(9,2);

DECLARE rgtrs CURSOR FOR (
select cxt.caixactrl, cxt.sigla, fpg.descricao, cxt.valor
from caixatotalizador01 cxt
inner join formapgto fpg on cxt.formapgto = fpg.codigo
where cxt.formapgto in (1,2,3) and cxt.caixactrl = nrocx
);
DECLARE CONTINUE HANDLER FOR NOT FOUND SET done = 1;

set vlrdin = 0;
set vlrcar = 0;
set vlrchq = 0;

OPEN rgtrs;

REPEAT
FETCH rgtrs INTO cx, sg, dc, vl;

if sg in (SU,VD, RB) then
if dc = DINHEIRO then set vlrdin = vlrdin + vl; end if;
if dc = TEF then set vlrcar = vlrcar + vl; end if;
if dc = CHEQUE then set vlrchq = vlrchq + vl; end if;
else
if sg = SA then
if dc = DINHEIRO then set vlrdin = vlrdin - vl; end if;
if dc = TEF then set vlrcar = vlrcar - vl; end if;
if dc = CHEQUE then set vlrchq = vlrchq - vl; end if;
end if;
end if;

UNTIL done END REPEAT;

CLOSE rgtrs;
END;
GOSTEI 0
Vagner Almeida

Vagner Almeida

25/05/2012

resolvido....
GOSTEI 0
POSTAR