MySQL Procedure with Pre-Select Data for Cursor - mysql

So,
I am facing a problem here, that is makeing me crazy, I think this is a stupid error, so I am not a newbie in MySQL but its not working like I think.
After try to deploy this statment to MySQL I got this Erro:
ERROR 1064 (42000): 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 'DEClARE estoque CURSOR FOR
SELECT
validade,
' at line 26
Here is my SP
DROP PROCEDURE IF EXISTS SP_SEPARA_MATERIAL;
DELIMITER $$
CREATE PROCEDURE SP_SEPARA_MATERIAL(IN MovimentoItemPedidoID INT(11))
BEGIN
DECLARE EMPRESA_ID int;
DECLARE MOVIMENTO_ID int;
DECLARE ARMAZEM_ID int;
DECLARE CLIENTE_ID int;
DECLARE FLUXO_LOGISTICO_ID int;
DECLARE PRODUTO_ID int;
DECLARE VOLUME_ID int;
DECLARE VALIDADE date;
DECLARE LOTE int;
DECLARE NOTA int;
DECLARE PRECO double;
DECLARE QTD_BOM double;
DECLARE QTD_RUIM double;
DECLARE ESTOQUE_BOM double;
DECLARE ESTOQUE_RUIM double;
DECLARE RET_BOM double;
DECLARE RET_RUIM double;
DECLARE finished INTEGER DEFAULT 0;
-- Catch head data of move
SELECT movimento_id, fluxo_logistico_id, produto_id, quantidade_bom, quantidade_ruim INTO MOVIMENTO_ID, FLUXO_LOGISTICO_ID, PRODUTO_ID, QTD_BOM, QTD_RUIM FROM movimento_itens_pedido WHERE id = MovimentoItemPedidoID;
SELECT empresa_id, cliente_id, armazem_id INTO EMPRESA_ID, CLIENTE_ID, ARMAZEM_ID FROM movimento WHERE id = MOVIMENTO_ID;
DEClARE estoque CURSOR FOR
SELECT
validade,
lote_numero,
nota_numero,
preco_unitario,
volume_id,
quantidade_bom,
quantidade_ruim
FROM
estoque_enderecado_reserva_picking
WHERE
empresa_id = EMPRESA_ID AND
armazem_id = ARMAZEM_ID AND
cliente_id = CLIENTE_ID AND
produto_id = PRODUTO_ID AND
(quantidade_bom>=0 OR quantidade_ruim>=0);
DECLARE CONTINUE HANDLER FOR NOT FOUND SET finished = 1;
OPEN estoque;
loop_separacao: LOOP
FETCH estoque INTO
VALIDADE,
LOTE,
NOTA,
PRECO,
VOLUME_ID,
ESTOQUE_BOM,
ESTOQUE_RUIM;
IF finished = 1 THEN
LEAVE loop_separacao;
END IF;
IF QTD_BOM>0 AND ESTOQUE_BOM>0 THEN
SET RET_BOM = 0;
IF ESTOQUE_BOM>=QTD_BOM THEN
SET RET_BOM = QTD_BOM;
ELSE
SET RET_BOM = ESTOQUE_BOM;
END IF;
END IF;
IF QTD_RUIM>0 AND ESTOQUE_RUIM>0 THEN
SET RET_RUIM = 0;
IF ESTOQUE_RUIM>=QTD_RUIM THEN
SET RET_RUIM = QTD_RUIM;
ELSE
SET RET_RUIM = ESTOQUE_RUIM;
END IF;
END IF;
IF RET_BOM>0 OR RET_RUIM>0 THEN
INSERT INTO movimento_picking_volume_itens (movimento_id,armazem_id,cliente_id,fluxo_logistico_id,produto_id,quantidade_bom,quantidade_ruim,validade,lote_numero,nota_numero,preco_unitario,volume_id)
VALUES (MOVIMENTO_ID,ARMAZEM_ID,CLIENTE_ID,FLUXO_LOGISTICO_ID,PRODUTO_ID,RET_BOM,RET_RUIM,VALIDADE,LOTE,NOTA,PRECO,VOLUME_ID);
SET QTD_BOM = (QTD_BOM - RET_BOM);
SET QTD_RUIM = (QTD_RUIM - RET_RUIM);
END IF;
IF QTD_BOM=0 AND QTD_RUIM=0 THEN
SET finished = 1;
LEAVE loop_separacao;
END IF;
END LOOP loop_separacao;
CLOSE estoque;
END $$
DELIMITER ;

Check: 13.6.6.2 Cursor DECLARE Syntax
...
Cursor declarations must appear before handler declarations and after
variable and condition declarations.
...
Try:
DROP PROCEDURE IF EXISTS SP_SEPARA_MATERIAL;
DELIMITER $$
CREATE PROCEDURE SP_SEPARA_MATERIAL(IN MovimentoItemPedidoID INT(11))
BEGIN
DECLARE EMPRESA_ID int;
DECLARE MOVIMENTO_ID int;
DECLARE ARMAZEM_ID int;
DECLARE CLIENTE_ID int;
DECLARE FLUXO_LOGISTICO_ID int;
DECLARE PRODUTO_ID int;
DECLARE VOLUME_ID int;
DECLARE VALIDADE date;
DECLARE LOTE int;
DECLARE NOTA int;
DECLARE PRECO double;
DECLARE QTD_BOM double;
DECLARE QTD_RUIM double;
DECLARE ESTOQUE_BOM double;
DECLARE ESTOQUE_RUIM double;
DECLARE RET_BOM double;
DECLARE RET_RUIM double;
DECLARE finished INTEGER DEFAULT 0;
/* MOVE AFTER THE DECLARE CONTINUE HANDLER ...
-- Catch head data of move
SELECT movimento_id, fluxo_logistico_id, produto_id, quantidade_bom, quantidade_ruim INTO MOVIMENTO_ID, FLUXO_LOGISTICO_ID, PRODUTO_ID, QTD_BOM, QTD_RUIM FROM movimento_itens_pedido WHERE id = MovimentoItemPedidoID;
SELECT empresa_id, cliente_id, armazem_id INTO EMPRESA_ID, CLIENTE_ID, ARMAZEM_ID FROM movimento WHERE id = MOVIMENTO_ID;
MOVE AFTER THE DECLARE CONTINUE HANDLER ... */
DEClARE estoque CURSOR FOR
SELECT
validade,
lote_numero,
nota_numero,
preco_unitario,
volume_id,
quantidade_bom,
quantidade_ruim
FROM
estoque_enderecado_reserva_picking
WHERE
empresa_id = EMPRESA_ID AND
armazem_id = ARMAZEM_ID AND
cliente_id = CLIENTE_ID AND
produto_id = PRODUTO_ID AND
(quantidade_bom>=0 OR quantidade_ruim>=0);
DECLARE CONTINUE HANDLER FOR NOT FOUND SET finished = 1;
-- Catch head data of move
SELECT movimento_id, fluxo_logistico_id, produto_id, quantidade_bom, quantidade_ruim INTO MOVIMENTO_ID, FLUXO_LOGISTICO_ID, PRODUTO_ID, QTD_BOM, QTD_RUIM FROM movimento_itens_pedido WHERE id = MovimentoItemPedidoID;
SELECT empresa_id, cliente_id, armazem_id INTO EMPRESA_ID, CLIENTE_ID, ARMAZEM_ID FROM movimento WHERE id = MOVIMENTO_ID;
OPEN estoque;
loop_separacao: LOOP
FETCH estoque INTO
VALIDADE,
LOTE,
NOTA,
PRECO,
VOLUME_ID,
ESTOQUE_BOM,
ESTOQUE_RUIM;
IF finished = 1 THEN
LEAVE loop_separacao;
END IF;
IF QTD_BOM>0 AND ESTOQUE_BOM>0 THEN
SET RET_BOM = 0;
IF ESTOQUE_BOM>=QTD_BOM THEN
SET RET_BOM = QTD_BOM;
ELSE
SET RET_BOM = ESTOQUE_BOM;
END IF;
END IF;
IF QTD_RUIM>0 AND ESTOQUE_RUIM>0 THEN
SET RET_RUIM = 0;
IF ESTOQUE_RUIM>=QTD_RUIM THEN
SET RET_RUIM = QTD_RUIM;
ELSE
SET RET_RUIM = ESTOQUE_RUIM;
END IF;
END IF;
IF RET_BOM>0 OR RET_RUIM>0 THEN
INSERT INTO movimento_picking_volume_itens (movimento_id,armazem_id,cliente_id,fluxo_logistico_id,produto_id,quantidade_bom,quantidade_ruim,validade,lote_numero,nota_numero,preco_unitario,volume_id)
VALUES (MOVIMENTO_ID,ARMAZEM_ID,CLIENTE_ID,FLUXO_LOGISTICO_ID,PRODUTO_ID,RET_BOM,RET_RUIM,VALIDADE,LOTE,NOTA,PRECO,VOLUME_ID);
SET QTD_BOM = (QTD_BOM - RET_BOM);
SET QTD_RUIM = (QTD_RUIM - RET_RUIM);
END IF;
IF QTD_BOM=0 AND QTD_RUIM=0 THEN
SET finished = 1;
LEAVE loop_separacao;
END IF;
END LOOP loop_separacao;
CLOSE estoque;
END $$
DELIMITER ;

Related

MySQL stored procedure syntax error for cursor select

DROP PROCEDURE CREATE_DUPLICATE_PRODUCT;
DELIMITER $$
CREATE PROCEDURE `CREATE_DUPLICATE_PRODUCT`(IN `old_course_id` INT(25), IN `new_course_id`
INT(25))
BEGIN
DECLARE db_cursor CURSOR FOR SELECT lic.org_id, lic.course_id, lic.license_duration_typeid, lic.insert_date, lic.insert_by, lic.quantity FROM cdp_organization_licenses as lic JOIN cdp_organization_license_settings as sett ON sett.org_license_id = lic.id JOIN cdp_organization_purchases as pur ON pur.org_id = lic.org_id AND pur.course_id = lic.course_id JOIN cdp_organizations as org ON org.org_id = lic.org_id WHERE lic.status_id = 1 AND org.status_id = 1;
DECLARE #org_id INT;
DECLARE #course_id INT;
DECLARE #license_typeid INT;
DECLARE #insert_date INT;
DECLARE #insert_by INT;
DECLARE #quantity INT;
OPEN db_cursor;
FETCH NEXT FROM db_cursor INTO #org_id, #course_id,
#license_duration_typeid, #insert_date, #insert_by, #quantity;
WHILE ##FETCH_STATUS = 0
BEGIN
--Do stuff with scalar values
FETCH NEXT FROM db_cursor INTO #org_id, #course_id,
#license_duration_typeid, #insert_date, #insert_by, #quantity;
INSERT INTO cdp_organization_licenses_test
SET
org_id = #org_id,
course_id = #course_id,
license_duration_typeid = #license_duration_typeid,
insert_date = #insert_date,
insert_by = #insert_by,
quantity = #quantity;
END;
CLOSE db_cursor;
DEALLOCATE db_cursor;
END$$
DELIMITER ;
I am getting this error:
#1064 - 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 '#org_id INT;
DECLARE #course_id INT;
DECLARE #license_typeid INT; ' at line 5
What can I do to resolve this?
You are mixing sql serv and mysql , that can not work
DROP PROCEDURE CREATE_DUPLICATE_PRODUCT;
DELIMITER $$
CREATE PROCEDURE `CREATE_DUPLICATE_PRODUCT`(IN `old_course_id` INT(25), IN `new_course_id`
INT(25))
BEGIN
DECLARE _org_id INT;
DECLARE _course_id INT;
DECLARE _license_typeid INT;
DECLARE _insert_date INT;
DECLARE _insert_by INT;
DECLARE _quantity INT;
DECLARE finished INTEGER DEFAULT 0;
DECLARE db_cursor CURSOR FOR
SELECT lic.org_id, lic.course_id, lic.license_duration_typeid, lic.insert_date, lic.insert_by, lic.quantity
FROM cdp_organization_licenses as lic
JOIN cdp_organization_license_settings as sett ON sett.org_license_id = lic.id
JOIN cdp_organization_purchases as pur ON pur.org_id = lic.org_id AND pur.course_id = lic.course_id
JOIN cdp_organizations as org ON org.org_id = lic.org_id
WHERE lic.status_id = 1 AND org.status_id = 1;
DECLARE CONTINUE HANDLER
FOR NOT FOUND SET finished = 1;
OPEN db_cursor;
getinfo: LOOP
BEGIN
FETCH NEXT FROM db_cursor INTO _org_id, _course_id,
_license_duration_typeid, _insert_date, _insert_by, _quantity;
IF finished = 1 THEN
LEAVE getEmail;
END IF;
INSERT INTO cdp_organization_licenses_test
SET
org_id = _org_id,
course_id = _course_id,
license_duration_typeid = _license_duration_typeid,
insert_date = _insert_date,
insert_by = _insert_by,
quantity = _quantity;
END;
END LOOP getinfo;
CLOSE db_cursor;
END$$
DELIMITER ;
But t´you can simply do a
INSERT INTO cdp_organization_licenses_test
SELECT lic.org_id, lic.course_id, lic.license_duration_typeid, lic.insert_date, lic.insert_by, lic.quantity
FROM cdp_organization_licenses as lic
JOIN cdp_organization_license_settings as sett ON sett.org_license_id = lic.id
JOIN cdp_organization_purchases as pur ON pur.org_id = lic.org_id AND pur.course_id = lic.course_id
JOIN cdp_organizations as org ON org.org_id = lic.org_id
WHERE lic.status_id = 1 AND org.status_id = 1;
That makes all with out the loop
Don't DECLARE variables with # at the beginning of their names. Those are session variables, don't need to be declared, and have session-wide scope,

mysql CURSOR - UNABLE TO ITERATE THROUGH THE RECORDS

THE CURSOR IS NOT GOING TO THE ELSE STATEMENT. WHAT AM I DOING WRONG? HOW CAN I DEBUG IN MYSQL ?
I am trying to get the list of task Ids with null values and then for each taskID, I am calling a SP to create start data and due date of the missing tasks(greater than the max(start_date available) until the current_date
DROP PROCEDURE IF EXISTS zcursor_ADDTA1;
DELIMITER ;;
CREATE PROCEDURE zcursor_ADDTA1(
#out retCount int
)
BEGIN
#DECLARE C_ID INT;
DECLARE C_TASK_ID INT;
DECLARE C_pattern varchar(100);
DECLARE C_REM INT;
DECLARE ACT_T_STTM VARCHAR(100);
DECLARE ACT_T_DTTM VARCHAR(100);
DECLARE TZ VARCHAR(100);
DECLARE T_STDT DATE;
DECLARE T_EXDT DATE;
DECLARE retCount INT;
DECLARE done INT DEFAULT FALSE;
DECLARE TA_MAX_ST_DT DATE;
#DECLARE P1 INT;
DECLARE cursor_i CURSOR FOR SELECT TASK_ID, PATTERN, reminder_days_before, ACTUAL_TASK_START_TIME,ACTUAL_TASK_DUE_TIME,TIMEZONE,
START_DT,EXP_DT FROM OCC_ML_TASK_RECURRENCE TR WHERE PATTERN = 'DAILY' AND CALENDAR_TYPE='' AND IS_CANCELED =0 AND EXP_DT>CURRENT_DATE();
DECLARE CONTINUE HANDLER FOR NOT FOUND SET done = TRUE;
SET retCount = 0;
OPEN cursor_i;
read_loop: LOOP
FETCH NEXT FROM cursor_i INTO C_TASK_ID,C_pattern,C_REM,ACT_T_STTM,ACT_T_DTTM,
TZ,T_STDT,T_EXDT;
IF done THEN
LEAVE read_loop;
ELSE
SELECT MAX(TA.START_DTM)FROM
OCC_ML_TASK_ACTIVITY TA
WHERE TA.TASK_ID=C_TASK_ID INTO TA_MAX_ST_DT;
SELECT DATE_ADD(TA_MAX_ST_DT,INTERVAL 1 DAY) INTO TA_MAX_ST_DT;
WHILE (TA_MAX_ST_DT<=CURRENT_DATE())
DO
BEGIN
IF WEEKDAY(TA_MAX_ST_DT)=4 THEN
CALL ZTA_MISSINGDATA_INSERT(C_TASK_ID ,TA_MAX_ST_DT);
SELECT DATE_ADD(TA_MAX_ST_DT,INTERVAL 3 DAY)INTO TA_MAX_ST_DT;
ELSEIF WEEKDAY(TA_MAX_ST_DT)=5 THEN
#"NO INSERT "
SELECT DATE_ADD(TA_MAX_ST_DT,INTERVAL 2 DAY)INTO TA_MAX_ST_DT;
ELSEIF WEEKDAY(TA_MAX_ST_DT)=6 THEN
#"NO INSERT "
SELECT DATE_ADD(TA_MAX_ST_DT,INTERVAL 1 DAY)INTO TA_MAX_ST_DT;
ELSE
CALL ZTA_MISSINGDATA_INSERT(C_TASK_ID ,TA_MAX_ST_DT);
SELECT DATE_ADD(TA_MAX_ST_DT,INTERVAL 1 DAY) INTO TA_MAX_ST_DT;
END IF;
END;
END WHILE;
END IF;
END LOOP;
CLOSE cursor_i;
END;
;;

mysql procedure : syntax, syntax, syntax ...... too hard to find

Here is my procedure :
delimiter //
drop procedure if exists migContactToActor;
create procedure migContactToActor()
begin
declare vctaid int;
declare firstname char(255);
declare lastname char(255);
declare phone char(255);
declare cellphone char(255);
declare fax char(255);
declare mail char(255);
declare location char(255);
declare extcode char(255);
declare vcpyid int;
declare vquaid int;
declare userModif char(255);
declare entityIdResp int;
declare niveauCreat char(255) default "contactMigration2.21";
declare userCreat char(255) default "contactMigration2.21";
declare backIdResp int;
declare userIdResp int;
declare zipcode char(255);
declare country char(255);
declare dateModif char(255);
declare dateCreated char(255);
declare dateRelation char(255);
declare groupLabel char(255);
declare adminLogId int;
declare finContact boolean default 0;
declare ctt int default 1; /* decompte contacts */
declare entityName char(255) default ''; /* entite courante du user a linker */
declare entityId int default 0; /* et son Id */
declare vctaidPrev int default 0;
declare curs1 cursor for select
ctaid, ctafirstname,ctalastname,ctaphone,ctacellphone,ctaemail,
substr(concat_ws(' ',ctaaddress,ctaaddress2,ctacity,ctazipcode),1,255),ctacode, cpyid,quaid,C.enoid_resp,
ctafax,C.actid_bck,ctadate_created,ctacountry,ctadate_modified,C.actid_resp,ctauser_modified, G.hemlabel, R.sync_update
from contact C
left join hd_contact_group_relationship R on R.hbhid = C.ctaid
left join hd_contact_group G on G.hemid = R.hemid
where !ifnull(C.ctaflagdeleted,0) and !ifnull(G.hemflag_deleted,0);
declare continue handler for not found set finContact = 1;
declare continue handler for sqlexception
begin
rollback;
end;
select '======== debut ...';
drop table if exists ent221;
create temporary table ent221 as select enoid, enoname from entityowner where enoname like 'CLI.CG_%.CLI';
alter table ent221 add index(enoname); /* not unique in dev, fetch the first in prod if any */
set autocommit = 0; /* TTT */
start transaction; /* TTT */
open curs1;
contactloop:loop
fetch curs1 into vctaid, firstname,lastname,phone,cellphone,mail,location,extcode,vcpyid,vquaid,entityIdResp,
fax,backIdResp,dateCreated,country,dateModif,userIdResp,userModif,groupLabel,dateRelation;
if finContact then
close curs1;
leave contactloop;
end if;
if vctaid = vctaidPrev then
set vctaidPrev = vctaid;
if (mod(ctt,100) = 0) then
set #msg = concat(ctt, ' contacts migrated');
select #msg;
end if;
update OPMSequence set counter = (#wbuf1 := counter) + 1 where name = 'ACTOR';
insert into actor (actid,cpyid,actlastname,actfirstname,actemail,actphone,actmobilephone,
actlocalisation, actid_responsible_owner,actid_backup_owner,enoid_responsible_owner,
actuser_created,actniveau_created, actdate_created,actuser_modified,
actdate_modified,actcountry,actfax,actqualifid,actexternal_code)
values
(#wbuf1,vcpyid,lastname,firstname,mail,phone,cellphone,location,userIdResp,backIdResp,entityIdResp,
userCreat,niveauCreat,dateCreated,userModif,dateModif,country,fax,vquaid,extcode);
update adminLog set adltype = 'User', adlobject_id = #wbuf1,
adlobject_description = concat(adlobject_description,'//oldContact=',vctaid)
where adlobject_id = vctaid and adltype = 'Contact';
end if;
if groupLabel is not null then
set #entName = concat('CLI.CG_',groupLabel,'.CLI);
select enoid from ent221 where enoname = #entName limit 1 into #wbuf2;
if #wbuf2 is not null then
insert into actorentityrelationship (enoid,actid,aerdate_created,aerniveau_created) values
(#buf2,#wbuf1,dateRelation,niveauCreat);
enf if;
end if;
set ctt = ctt + 1;
end loop contactloop;
rollback; /* TTT */
end //
delimiter ;
call migContactToActor;
drop procedure migContactToActor;
Why this ???
Query OK, 0 rows affected, 1 warning (0.00 sec)
ERROR 1064 (42000): 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 ''.CLI);
select enoid from ent221 where enoname = #entName limit 1 into #wbuf2' at line 83
I think you missed the quotes
set #entName = concat('CLI.CG_',groupLabel,'.CLI);
with quotes
set #entName = concat('CLI.CG_',groupLabel,'.CLI');

How to create a cursor in Mysql Within Stored procedure

I have created a stored procedure where I need fetch all the records from complaint table and then loop through it and find out who commented when on the particular complaint. You can assume it as blog application where a blog can have multiple comment.
I am getting syntax error in
Declare cur CURSOR statement,
What could be the problem or what I am missing into this.
This is the following message I am getting
Error Code: 1064
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 'declare cur CURSOR for SELECT id,user_id FROM complaint3 WHERE user_id IN( SELEC' at line 22
Below is my procedure
DELIMITER $$
CREATE PROCEDURE `myDB`.`ShowResult`(user_id INT, hours INT,L_Complaint_id INT)
BEGIN
DECLARE complaint_count INT;
DECLARE 24Hrs_count INT;
DECLARE 48Hrs_count INT;
DECLARE Gr_48Hrs_count INT;
DECLARE notCommented INT;
DECLARE agentName VARCHAR(100);
DECLARE v_agentId INT;
DECLARE v_userId INT;
DECLARE lastUserCommentDate DATETIME;
DECLARE lastInternalUserCommentDate DATETIME;
DECLARE tempDate INT;
DECLARE v_complaint_id INT;
SET 24Hrs_count =0;
SET 48Hrs_count =0;
SET Gr_48Hrs_count =0;
SET notCommented =0;
SET v_complaint_id =0;
DECLARE cur CURSOR FOR SELECT id,user_id FROM complaint3 WHERE user_id IN( SELECT id FROM user3 WHERE user_type=0);
CREATE TEMPORARY TABLE IF NOT EXISTS resultTable (
id MEDIUMINT NOT NULL AUTO_INCREMENT,t_agentId INT,t_agentName VARCHAR(1000),t_24HrsCount INT,t_48HrsCount INT,t_Gr48HrsCount INT,
t_nullCount INT,PRIMARY KEY (id)) ENGINE = MEMORY;
SELECT COUNT(DISTINCT(id)) INTO complaint_count FROM complaint3 WHERE user_id IN(SELECT id FROM user3 WHERE user_type=0);
OPEN cur;
insert_loop: LOOP
IF complaint_count > 0 THEN
FETCH cur INTO complaint_id,user_id;
SELECT created_at INTO lastUserCommentDate FROM complaint3_diary WHERE complaint_id=v_complaint_id AND user_id = v_user_id ORDER BY id DESC LIMIT 1;
SELECT assigned_to INTO v_agentId FROM assignment3 WHERE complaint_id=v_complaint_id AND a.expire_at IS NULL;
SELECT NAME INTO agentName FROM user3 WHERE id=v_agentId;
SELECT created_at INTO lastInternalUserCommentDate FROM complaint3_diary WHERE complaint_id=v_complaint_id AND user_id = v_agentId ORDER BY id DESC LIMIT 1;
SELECT TIMESTAMPDIFF(HOUR, lastInternalUserCommentDate, lastUserCommentDate) INTO tempDate;
IF (tempDate >0 && tempDate <= 24) THEN
SET 24Hrs_count =1;
ELSEIF (tempDate >24 && tempDate <= 48) THEN
SET 48Hrs_count = 1;
ELSEIF (tempDate >48) THEN
SET Gr_48Hrs_count = 1;
ELSE
SET notCommneted = 1;
END IF;
INSERT INTO resultTable(t_agentId,t_agentName,t_24HrsCount,t_48HrsCount,t_Gr48HrsCount,t_nullCount) VALUES(v_agentId,agentName,24Hrs_count,48Hrs_count,Gr_48Hrs_count,notCommneted);
ELSE
LEAVE insert_loop;
END IF;
SET complaint_count = complaint_count - 1;
END LOOP;
CLOSE cur;
SELECT t_agentId,t_agentName,COUNT(t_24HrsCount),COUNT(t_48HrsCount),COUNT(t_Gr48HrsCount),COUNT(t_nullCount) FROM resultTable GROUP BY agentId;
END$$
DELIMITER ;
As per documentation on DECLARE
DECLARE is permitted only inside a BEGIN ... END compound statement and must be at its start, before any other statements.
In your code, the statement
DECLARE cur CURSOR FOR
SELECT id, user_id
FROM complaint3
WHERE user_id IN( SELECT id FROM user3 WHERE user_type = 0 );
has no followed the declaration order rule. And hence is the error.
Change part of your code as following:
BEGIN
DECLARE complaint_count INT;
DECLARE 24Hrs_count INT;
DECLARE 48Hrs_count INT;
DECLARE Gr_48Hrs_count INT;
DECLARE notCommented INT;
DECLARE agentName VARCHAR(100);
DECLARE v_agentId INT;
DECLARE v_userId INT;
DECLARE lastUserCommentDate DATETIME;
DECLARE lastInternalUserCommentDate DATETIME;
DECLARE tempDate INT;
DECLARE v_complaint_id INT;
DECLARE cur CURSOR FOR
SELECT id, user_id
FROM complaint3
WHERE user_id IN( SELECT id FROM user3 WHERE user_type = 0 );
SET 24Hrs_count =0;
SET 48Hrs_count =0;
SET Gr_48Hrs_count =0;
SET notCommented =0;
SET v_complaint_id =0;

MySQL DateSub inside loop

I have a stored procedure like this :
DROP PROCEDURE IF EXISTS storedprocedure;
CREATE DEFINER = 'userid'#'%' PROCEDURE storedprocedure
(IN id int)
BEGIN
DECLARE cor int;
DECLARE sup int;
DECLARE faktur varchar(20);
DECLARE ptgs int;
DECLARE suppli varchar(50);
DECLARE bag int;
DECLARE brg int;
DECLARE qty int;
DECLARE beli int;
DECLARE net int;
DECLARE oldbeli int;
DECLARE oldnet int;
DECLARE updhrg int;
DECLARE ket varchar(100);
DECLARE idsisa int;
DECLARE qtyterima int;
DECLARE qtysisa int;
DECLARE no_more_rows BOOLEAN;
DECLARE loop_cntr INT DEFAULT 0;
DECLARE num_rows INT DEFAULT 0;
DECLARE hitung CURSOR FOR
SELECT
aptlog_orderterima.corp,
aptlog_orderterima.idsupplier,
aptlog_orderterima.faktur,
aptlog_orderterima.idpetugas,
aptlog_supplier.supplier,
aptlog_orderterima.idbagian,
aptlog_orderterimadetail.idbarang,
aptlog_orderterimadetail.beli,
aptlog_orderterimadetail.net,
aptlog_orderterimadetail.qty,
aptlog_barang.beli,
aptlog_barang.net,
aptlog_barang.updatehrg,
CONCAT(aptlog_orderterima.faktur,' From : ',aptlog_supplier.supplier)
FROM
aptlog_orderterima
RIGHT OUTER JOIN aptlog_orderterimadetail ON (aptlog_orderterima.id = aptlog_orderterimadetail.idterima)
LEFT OUTER JOIN aptlog_supplier ON (aptlog_orderterima.idsupplier = aptlog_supplier.id)
LEFT OUTER JOIN aptlog_barang ON (aptlog_orderterimadetail.idbarang = aptlog_barang.id)
WHERE
aptlog_orderterima.id = id;
DECLARE sisaorder CURSOR FOR
SELECT
aptlog_orderdetail.id,
aptlog_orderdetail.qtyterima,
aptlog_orderdetail.sisa
FROM
aptlog_orderdetail
LEFT OUTER JOIN aptlog_order ON (aptlog_orderdetail.idorder = aptlog_order.id)
WHERE
aptlog_order.corp=cor AND
aptlog_order.stat=2 AND
aptlog_order.idsupplier=sup AND
CAST(aptlog_order.waktu AS DATE) >= CURDATE()-(SELECT pengadaan_param.nilai FROM pengadaan_param WHERE pengadaan_param.id=2) AND
aptlog_orderdetail.sisa<>0 AND
aptlog_orderdetail.idbarang=brg
ORDER BY
aptlog_order.waktu
LIMIT 1;
DECLARE CONTINUE HANDLER FOR NOT FOUND
SET no_more_rows = TRUE;
OPEN hitung;
SELECT FOUND_ROWS() INTO num_rows;
the_loop: LOOP
FETCH hitung INTO cor, sup, faktur, ptgs, suppli, bag, brg, beli, net, qty, oldbeli, oldnet, updhrg, ket;
IF no_more_rows THEN CLOSE hitung; LEAVE the_loop;
END IF;
SET #awal = (SELECT aptlog_stok.qty FROM aptlog_stok WHERE corp=cor AND idbarang=brg AND idbagian=bag);
IF #awal IS NOT NULL THEN
UPDATE aptlog_stok SET aptlog_stok.qty = #awal + qty
WHERE corp=cor AND idbarang=brg AND idbagian=bag;
INSERT INTO aptlog_kartustok(waktu, corp, idbagian, idbarang, qtymasuk, qtykeluar, qtysisa, idpetugas, ket)
VALUES (now(), cor, bag, brg, qty, 0, #awal + qty, ptgs, ket); ELSE
INSERT INTO aptlog_stok(corp, idbarang, idbagian, qty)
VALUES (cor, brg, bag, qty);
INSERT INTO aptlog_kartustok(waktu, corp, idbagian, idbarang, qtymasuk, qtykeluar, qtysisa, idpetugas, ket)
VALUES (now(), cor, bag, brg, qty, 0, qty, ptgs, ket);
END IF;
IF updhrg=0 THEN
UPDATE aptlog_barang SET
aptlog_barang.beli=beli,
aptlog_barang.net=net,
aptlog_barang.updatehrg=1,
aptlog_barang.ubahharga=ket,
aptlog_barang.waktuubah=now(),
aptlog_barang.idpetugasubah=ptgs
WHERE
aptlog_barang.id=brg; ELSE
IF (updhrg=1) AND (beli > oldbeli) THEN
UPDATE aptlog_barang SET
aptlog_barang.beli=beli,
aptlog_barang.belilama=oldbeli,
aptlog_barang.net=net,
aptlog_barang.netlama=oldnet,
aptlog_barang.ubahharga=ket,
aptlog_barang.waktuubah=now(),
aptlog_barang.idpetugasubah=ptgs
WHERE
aptlog_barang.id=brg; END IF;
END IF;
SET #qty=qty;
sisa_order: LOOP
OPEN sisaorder;
FETCH sisaorder INTO idsisa, qtyterima, qtysisa;
IF #qty=0 THEN CLOSE sisaorder; LEAVE sisa_order;
END IF;
IF #qty <> 0 THEN
IF qtysisa > #qty THEN
UPDATE aptlog_orderdetail SET
aptlog_orderdetail.qtyterima=qtyterima+#qty,
aptlog_orderdetail.sisa=qtysisa-#qty
WHERE
aptlog_orderdetail.id=idsisa;
SET #qty=0;
ELSE
UPDATE aptlog_orderdetail SET
aptlog_orderdetail.qtyterima=qtyterima+qtysisa,
aptlog_orderdetail.sisa=0
WHERE
aptlog_orderdetail.id=idsisa;
SET #qty = #qty-qtysisa;
END IF;
END IF;
CLOSE sisaorder;
END LOOP sisa_order;
SET loop_cntr = loop_cntr + 1;
END LOOP the_loop;
END');
My question :
The second loop work perfectly, but the first loop just work once.
But if I remove this line "CAST(aptlog_order.waktu AS DATE) >= CURDATE()-(SELECT pengadaan_param.nilai FROM pengadaan_param WHERE pengadaan_param.id=2) AND" from sisaorder all loop work perfectly...
So can anybody help me?