Sytax error in mysql stored procedure - mysql

What is wrong in the syntax of the below stored procedure in MySQL ?
CREATE PROCEDURE curdemo()
BEGIN
DECLARE #isbn varchar(17)
DECLARE #count int
DECLARE #price float(6,2)
DECLARE #totalbookpriceValue float(6,2)
DECLARE totalbookprice CURSOR
STATIC FOR
(SELECT ISBN,COUNT(ISBN) FROM applieddb.cart c GROUP BY ISBN)
OPEN totalbookprice
IF ##CURSOR_ROWS > 0 BEGIN
FETCH NEXT FROM cur_emp INTO #isbn,#count
WHILE ##Fetch_status = 0
SELECT ISBN,PRICE FROM book INTO #price WHERE ISBN = #isbn
PRINT 'Total Book Price is' + #price * #count
FETCH NEXT FROM cur_emp INTO #isbn,#count
END
END
CLOSE totalbookprice
DEALLOCATE totalbookprice
SET NOCOUNT OFF
END
ERROR Message:
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 '#isbn varchar(17) DECLARE #count int DECLARE #price float(6,2) DECLARE #totalboo' at line 3
Changing the mysql query to the below also did not help and gave the following error:

DECLARE for local (without #) or SET for session (with #)

***The solution to the above problem is as below:***
CREATE DEFINER=`root`#`localhost` PROCEDURE `calculateTotalPrice`()
BEGIN
DECLARE done INT default 0;
DECLARE _isbn varchar(17);
DECLARE _count int;
DECLARE _price float(6,2);
DECLARE loop_cntr INT DEFAULT 0;
DECLARE _totalbookpriceValue float(6,2);
DECLARE totalbookprice CURSOR FOR SELECT ISBN,COUNT(ISBN) FROM applieddb.cart c GROUP BY ISBN;
DECLARE CONTINUE HANDLER FOR NOT FOUND set done= TRUE;
OPEN totalbookprice;
the_loop: LOOP
FETCH totalbookprice into _isbn,_count;
SET _price= (SELECT b.price from book b where b.ISBN = _isbn);
SET _totalbookpriceValue= _price*_count;
SELECT _totalbookpriceValue;
IF done THEN
CLOSE totalbookprice;
LEAVE the_loop;
END IF;
-- count the number of times looped
SET loop_cntr = loop_cntr + 1;
END LOOP the_loop;
END

Related

Mysql Store procedure stops iteration after some rows

Below procedure code running with out error . Line select FOUND_ROWS() returning n no. rows but cursor curs did not loop all rows
CREATE DEFINER=`root`#`%` PROCEDURE `middleLocationAutoUpdatePorc`()
BEGIN
declare vname varchar(45);
declare vmobile varchar(20);
declare vsapid varchar(6);
declare vuser varchar(45);
declare vday date;
declare vmintime time;
declare vmaxtime time;
declare vminLocation mediumtext;
declare vmaxLocation mediumtext;
declare vmiddlelocation mediumtext;
declare vdistance int(11);
declare vdrdid int(11);
declare vn_no_details int(11);
declare uatt varchar(45) default 'X';
declare adatta varchar(45) default 'X';
declare b_not_found BOOL DEFAULT FALSE;
declare curs CURSOR FOR
SELECT user ,day, mintime,maxtime_mobile,minLocation,maxLocation,distance,n_no_details,drdid FROM mydb.statusreport where day >= '2017-06-26';
DECLARE CONTINUE HANDLER FOR NOT FOUND SET b_not_found = true;
OPEN curs;
loop1: LOOP
FETCH curs INTO vuser,vday,vmintime,vmaxtime,vminLocation,vmaxLocation,vdistance,vn_no_details,vdrdid;
IF b_not_found THEN
LEAVE loop1;
END IF;
-- select FOUND_ROWS();
case substring_index(vuser,"-",-1)
when 'RSM' then
select username,Name,mobile into vsapid,vname,vmobile from mydb.supervisor where idSu=CONVERT(substring_index(vuser,"-",1),UNSIGNED INTEGER);
when 'ASM' then
select userName,name,mobile into vsapid,vname,vmobile from mydb.executive where exeid=CONVERT(substring_index(vuser,"-",1),UNSIGNED INTEGER);
when 'F' then
select sapId,name,phone into vsapid,vname,vmobile from mydb.user where idUser=CONVERT(substring_index(vuser,"-",1),UNSIGNED INTEGER);
end case;
select userGiven , adminGiven into uatt ,adatta from userdaystatus st where st.date =vday and st.idUser=CONVERT(substring_index(vuser,"-",1),UNSIGNED INTEGER) and st.userType=substring_index(vuser,"-",-1);
set vmiddlelocation=( select location from mydb.dailyReportDetails as dtb where dtb.idDailyReport=vdrdid and dtb.counter>=(abs(vn_no_details/2) ) order by dtb.idDailyReportDetails asc limit 1);
call mydb.addOMiddleLocation(day(vday), month(vday),
year(vday),vuser, vname,
vsapid, vmobile, vmintime,
vmaxtime, SUBTIME(vmaxtime,vmintime),
vminLocation,
vmiddlelocation,
vmaxLocation,Round(vdistance/1000,2),
uatt, adatta);
END LOOP;
CLOSE curs;
END
The Procedure call mydb.addOMiddleLocation() just inserting Row on another table.There does not have any data type validation .
So what can be the problem ?
It happen for log wait time for a particular Query line
set vmiddlelocation=( select location from mydb.dailyReportDetails as dtb where dtb.idDailyReport=vdrdid and dtb.counter>=(abs(vn_no_details/2) ) order by dtb.idDailyReportDetails asc limit 1);

Cursor to copy distinct record from one table to another

I want to copy all recoreds from temp1 table to anoter two tables I am using cursor for this .
DELIMITER //
CREATE PROCEDURE cpyQ()
BEGIN
DECLARE g_id INT DEFAULT 0;
DECLARE v_fn varchar(100);
DECLARE v_ln varchar(100);
DECLARE v_email varchar(100);
declare tcursor for select distinct mailid,fname,lname from temp1;
DECLARE CONTINUE HANDLER FOR NOT FOUND SET flag = 1;
OPEN tcursor;
REPEAT
FETCH cursor into v_fn,v_ln, v_email;
insert into atom(type) values('Person');
SET g_id = LAST_INSERT_ID();
insert into user(id,fname,lname,mailid) values(g_id,v_fname,v_lname,v_email);
END REPEAT;
CLOSE tcursor;
END//
DELIMITER
this code is showing error
MySQL said: Documentation
#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 'for select distinct mailid,fname,lname from temp1;
DECLARE CONTINUE HANDLE' at line 8
How to resolve this
You have multiple errors in your syntax and don't exit the loop. Try this?
CREATE PROCEDURE cpyQ()
BEGIN
DECLARE g_id INT DEFAULT 0;
DECLARE v_fn varchar(100);
DECLARE v_ln varchar(100);
DECLARE v_email varchar(100);
DECLARE done INT DEFAULT FALSE;
declare tcursor cursor for select distinct mailid,fname,lname from temp1;
DECLARE CONTINUE HANDLER FOR NOT FOUND SET done = TRUE;
OPEN tcursor;
read_loop: LOOP
FETCH tcursor into v_fn,v_ln, v_email;
if done then
LEAVE read_loop;
END IF;
insert into atom(type) values('Person');
SET g_id = LAST_INSERT_ID();
insert into user(id,fname,lname,mailid) values(g_id,v_fn,v_ln,v_email);
END LOOP;
CLOSE tcursor;
END
I tried this query and find this is working
insert into atom(id,type) select id,'Person' from user1;
INSERT INTO user( id, fname, lname, mailid ) SELECT id, fname, lname, mailid FROM user1;

cursor not working in stored procedure it throwing 1064 error

I want to use cursor in my project but it throwing a error 1064. Please help me in resolving the problem.....
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 curs1 CURSOR FOR SELECT healthinsurancepremium.productid ,healthinsuran' at line 63
My Procedure code:
CR-EATE DEFINER=`root`#`localhost` PROCEDURE `spGettestOffline` (
IN in_sumassured INT(10),
IN in_age INT(3),
IN in_adult INT(4),
IN in_child INT(4),
IN in_tenure INT(3),
IN in_city VARCHAR(20)
)
BEGIN
DECLARE bDone INT DEFAULT 0;
DECLARE var1 INT ;
DECLARE Var2 INT;
DECLARE Var3 INT;
DECLARE var4 INT;
/* this is the table declaration */
DROP TEMPORARY TABLE IF EXISTS tblResults;
CREATE TEMPORARY TABLE IF NOT EXISTS tblResults (
productid INT,
suminsured INT,
amount INT,
tenent INT
);
/* this is the cursor declaration */
DECLARE curs1 CURSOR FOR SELECT healthinsurancepremium.productid ,healthinsurancepremium.suminsured ,healthinsurancepremium.amount ,healthinsurancepremium.tenure FROM healthinsurancepremium LEFT JOIN `cityspecifichealthpremium` ON `healthinsurancepremium`.`id` >= `cityspecifichealthpremium`.`healthpremiumidmin` AND `healthinsurancepremium`.`id` <= `cityspecifichealthpremium`.`healthpremiumidmax` WHERE (`cityspecifichealthpremium`.`healthpremiumidmax` IS NULL AND `cityspecifichealthpremium`.`healthpremiumidmin` IS NULL) AND healthinsurancepremium.suminsured = in_sumassured AND in_age >=healthinsurancepremium.minage AND in_age <=healthinsurancepremium.maxage AND healthinsurancepremium.adult=in_adult AND healthinsurancepremium.child=in_child ;
/* this is the cursor looping */
DECLARE CONTINUE HANDLER FOR NOT FOUND SET bDone = 1;
OPEN curs1;
read_loop: LOOP
FETCH curs1 INTO var1,var2,var3,var4;
INSERT INTO tblResults VALUES (var1,var2, var3,var4);
IF (bDone = 1) THEN
LEAVE read_loop;
END IF;
END LOOP;
CLOSE curs1;
SELECT * FROM tblResults;
END$$
I think this problem belongs to the cursor declaration part.... but I did not find anything on it
You have put the DECLARE statement at a wrong place.
Usage condition on DECLARE statements:
You must DECLARE them explicitly at the start of the BEGIN/END block, along with their data types.
Move all your DECLARE ... statements to start of the BEGIN block.
It should look like:
BEGIN
DECLARE bDone INT DEFAULT 0;
DECLARE var1 INT ;
DECLARE Var2 INT;
DECLARE Var3 INT;
DECLARE var4 INT;
DECLARE curs1 CURSOR FOR
SELECT
healthinsurancepremium.productid,
healthinsurancepremium.suminsured,
healthinsurancepremium.amount,
healthinsurancepremium.tenure
FROM healthinsurancepremium
LEFT JOIN `cityspecifichealthpremium` ON
`healthinsurancepremium`.`id` >= `cityspecifichealthpremium`.`healthpremiumidmin` AND
`healthinsurancepremium`.`id` <= `cityspecifichealthpremium`.`healthpremiumidmax`
WHERE
( `cityspecifichealthpremium`.`healthpremiumidmax` IS NULL AND
`cityspecifichealthpremium`.`healthpremiumidmin` IS NULL ) AND
healthinsurancepremium.suminsured = in_sumassured AND
in_age >= healthinsurancepremium.minage AND
in_age <= healthinsurancepremium.maxage AND
healthinsurancepremium.adult = in_adult AND
healthinsurancepremium.child = in_child ;
Refer to: Stored Procedures - MySQL

Error in Stored procedure (Error Code : 1064)

My stored procedure is like this ...
DELIMITER $$
DROP PROCEDURE IF EXISTS `tds_dev`.`BlockTokenSheduler`$$
CREATE PROCEDURE `BlockTokenSheduler`(cdate date,shift varchar(20))
BEGIN
declare lo_SERIALNO int;
declare lo_TOKENNUMBER int;
declare lo_ARRIVALTIME time;
declare lo_ADJUSTMENTTIME time;
declare lo_APPOINTMENTTIME time;
declare bt_ADJUSTMENTTIME time;
declare bt_NEXTAPPOINTMENTTIME time;
declare lo_CONSULTATIONTYPE varchar(20);
declare lo_NEXTAPPOINTMENTTIME time;
declare lo_CONSULTATIONSTATUS varchar(20);
declare lo_ACTUALFINISHEDTIME time;
declare lo_SMSSTATUS varchar(20);
declare temp_appTime time;
declare time_diff time;
declare done int;
declare btdone int;
declare btcount int;
declare co int;
Declare btcountcur Cursor for
select ADJUSTMENTTIME,NEXTAPPOINTMENTTIME from tds_tokengeneration where TOKENDATE =cdate and SHIFTID = shift and blockstatus='BT' ORDER BY APPOINTMENTTIME ;
declare continue handler for not found set btdone=1;
open btcountcur;
bt_loop :LOOP
if btdone=1 then
leave bt_loop;
end if;
FETCH btcountcur into bt_ADJUSTMENTTIME,bt_NEXTAPPOINTMENTTIME;
Declare mycur cursor for
select TOKENNUMBER,APPOINTMENTTIME,ADJUSTMENTTIME,CONSULTATIONTYPE,NEXTAPPOINTMENTTIME,CONSULTATIONSTATUS,SMSSTATUS from tds_tokengeneration
where TOKENDATE=cdate and SHIFTID=shift and blockstatus='MT';
declare continue handler for not found set done=1;
open mycur;
time_loop :LOOP
FETCH mycur into lo_TOKENNUMBER,lo_APPOINTMENTTIME,lo_ADJUSTMENTTIME,
lo_CONSULTATIONTYPE,lo_NEXTAPPOINTMENTTIME,lo_CONSULTATIONSTATUS,lo_SMSSTATUS;
if done=1 then
leave time_loop;
end if;
if (lo_ADJUSTMENTTIME >= bt_ADJUSTMENTTIME and lo_APPOINTMENTTIME <= bt_NEXTAPPOINTMENTTIME) or (lo_NEXTAPPOINTMENTTIME >= bt_ADJUSTMENTTIME and lo_NEXTAPPOINTMENTTIME <= bt_NEXTAPPOINTMENTTIME)then
set lo_ADJUSTMENTTIME=bt_NEXTAPPOINTMENTTIME;
if lo_CONSULTATIONTYPE='C' then
set lo_NEXTAPPOINTMENTTIME = ADDTIME(lo_ADJUSTMENTTIME,'00:12:00');
else
set lo_NEXTAPPOINTMENTTIME = ADDTIME(lo_ADJUSTMENTTIME,'00:20:00');
end if;
update tds_tokengeneration set ADJUSTMENTTIME=lo_ADJUSTMENTTIME,
NEXTAPPOINTMENTTIME=lo_NEXTAPPOINTMENTTIME,
SMSSTATUS=lo_SMSSTATUS
where TOKENNUMBER=lo_TOKENNUMBER and TOKENDATE=cdate and SERIALNO=lo_SERIALNO;
end if;
end loop time_loop;
close mycur;
end loop bt_loop;
close btcountcur;
END$$
DELIMITER ;
.but when i executing this program i'm getting below error
(0 row(s)affected)
(0 ms taken)
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 mycur cursor for
select TOKENNUMBER,APPOINTMENTTIME,ADJ' at line 33
(0 ms taken)
Declarations must follow a certain order.
It is not allowed to declare a cursor or an event handler in the middle of your procedure. Yes, the error message is misleading to say the least. You must declare the mycur cursor at the beginning of a BEGIN ... END block.
You could either move the second cursor declaration to the beginning of your procedure, or nest a BEGIN ... END block at an appropriate location.

Issue in adding two outputs from MySQL function inside another function

CREATE DEFINER=`root`#`localhost` FUNCTION `F_GetProjectCostPerEmployeeInProject`(id VARCHAR(20)) RETURNS DECIMAL(30,2)
BEGIN
DECLARE e_id VARCHAR(20);
DECLARE finished INT ;
DECLARE temp DECIMAL(30,2);
DECLARE temp2 DECIMAL(30,2);
DECLARE TotalCostOfEmployees DECIMAL(30,2);
DECLARE cur CURSOR FOR SELECT DISTINCT e_id FROM project_employee WHERE project_id=id;
DECLARE CONTINUE HANDLER FOR NOT FOUND SET finished = 1;
emploop : LOOP
FETCH cur INTO e_id;
IF finished =1 ;
LEAVE emploop;
END IF ;
SET TotalCostOfEmployees = TotalCostOfEmployees + ( F_TotalManDaysPerEmployee(e_id,id)*(F_GetEmployeeGradeSal(e_id));
END LOOP emploop;
RETURN TotalCostOfEmployees;
END$$
The problem is its giving error at line :
SET TotalCostOfEmployees = TotalCostOfEmployees + ( F_TotalManDaysPerEmployee(e_id,id)*(F_GetEmployeeGradeSal(e_id));
This is the error :
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 '; leave emploop; end if ;
set TotalCostOfEmployees = TotalCostOfEmploy' at line 12
Use the SELECT ... INTO clause
SELECT TotalCostOfEmployees + ( F_TotalManDaysPerEmployee(e_id,id)*(F_GetEmployeeGradeSal(e_id))
INTO TotalCostOfEmployees;
Why are you using a cursor for this at all?
SELECT SUM(F_TotalManDaysPerEmployee(e_id, id) * F_GetEmployeeGradeSal(e_id)) AS TotalCostOfEmployees
FROM (
SELECT DISTINCT e_id
FROM project_employee
WHERE project_id = id
) q
I solved it via this way:
enter code BEGIN DECLARE e_id VARCHAR(20);
DECLARE finished INT ;
DECLARE salary DECIMAL(30,2);
DECLARE TotalCostOfEmployees DECIMAL(30,2) ;
DECLARE cur CURSOR FOR SELECT DISTINCT Emp_code FROM project_employee WHERE project_id=p_id;
DECLARE CONTINUE HANDLER FOR NOT FOUND SET finished = 1;
SET finished = 0;
OPEN cur;
SET TotalCostOfEmployees =0.0;
emploop : LOOP
FETCH cur INTO e_id;
IF finished = 1 THEN
LEAVE emploop;
END IF ;
SELECT COALESCE( (F_TotalManDaysPerEmployee(e_id,p_id)* F_GetEmployeeGradeSal(e_id))/22,0.0)
INTO salary;
SET TotalCostOfEmployees = TotalCostOfEmployees + salary;
/*SELECT (TotalCostOfEmployees + ifnull(salary,0.0)) into TotalCostOfEmployees; */
END LOOP emploop;
CLOSE cur;
RETURN TotalCostOfEmployees;
END$$