MySQL stores procedure cannot add values - mysql
DELIMITER $$
CREATE PROCEDURE GetCustomerLevel(p_barcode int)
BEGIN
DECLARE q1 int;
DECLARE q2 int;
DECLARE q3 int;
DECLARE total int;
SET total :=0;
SELECT sum(adjustment_quantity) INTO q1 FROM adjustment_inventory WHERE item_barcode = p_barcode group by adjustment_quantity;
SELECT sum(opening_stock) INTO q2 FROM openingstock
WHERE item_barcode = p_barcode group by opening_stock;
SELECT sum(inwardquantity) INTO q3
FROM inwardmaster WHERE item_barcode = p_barcode group by inwardquantity;
IF q1 IS NULL THEN
SET q1 := 0;
END IF;
IF q2 IS NULL THEN
SET q2 := 0;
END IF;
IF q3 IS NULL THEN
SET q3 := 0;
END IF;
SELECT q1;
SELECT q2;
SELECT q3;
SELECT q1+q2+q3;
END$$
It's return wrong answer everytime. For example q1=100 q2=200 q3=100 its return 100
you dont need to use stored procedure for this
set #barcode = '1234';
select
coalesce((
SELECT sum(coalesce(adjustment_quantity,0))
FROM adjustment_inventory
WHERE item_barcode = #p_barcode
),0) +
coalesce((
SELECT sum(opening_stock)
FROM openingstock
WHERE item_barcode = #p_barcode
), 0) +
coalesce((
SELECT
sum(coalesce(inwardquantity,0))
FROM inwardmaster WHERE item_barcode = #p_barcode
), 0) res
From Dual
;
If you really want to use procedure then check the code below
DELIMITER $$
CREATE PROCEDURE GetCustomerLevel(p_barcode int)
BEGIN
DECLARE q1 int;
DECLARE q2 int;
DECLARE q3 int;
DECLARE total int;
SET total :=0;
SELECT coalesce(sum(adjustment_quantity), 0) INTO q1 FROM adjustment_inventory WHERE item_barcode = p_barcode;
SELECT coalesce(sum(opening_stock), 0) INTO q2 FROM openingstockWHERE item_barcode = p_barcode;
SELECT coalesce(sum(inwardquantity), 0) INTO q3 FROM inwardmaster WHERE item_barcode = p_barcode;
SELECT q1;
SELECT q2;
SELECT q3;
set total = q1+q2+q3;
SELECT total;
END$$
Related
stored procedure returns null value
i am making a stored procedure to give cashback based on the total transactions by a single person a month but when called it shows null value for cashback get CREATE DEFINER=`root`#`localhost` PROCEDURE `stored_procedure_cashback`(IN a INT, IN b INT) BEGIN DECLARE cashback_get INT; DECLARE total INT; SELECT customers.`id_customers`, customers.`customers_name`, MONTH(transaction.`transaction_date`) AS month, YEAR(transaction.`transaction_date`) AS year, SUM((transaction_detail.`ammount`*transaction_detail.`price_per_piece`)-transaction_detail.`discount`) AS total, cashback_get FROM transaction_detail INNER JOIN transaction ON transaction_detail.`id_transaction`=transaction.`id_transaction` INNER JOIN customers ON transaction.`id_customers`=customers.`id_customers` WHERE MONTH(transaction.`transaction_date`) = a AND YEAR(transaction.`transaction_date`) = b GROUP BY customers.`id_customers`; IF (total >= 20000) THEN SET cashback_get = 2000; ELSE SET cashback_get = 0; END IF;
You mised to put the result as OUT parameter. CREATE DEFINER=`root`#`localhost` PROCEDURE. `stored_procedure_cashback`(IN a INT, IN b INT, OUT cashback_get INT) BEGIN DECLARE total INT; SELECT Sum( etc etc) into total From table etc etc IF total >= 20000 Then SET cashback_get = 2000; ELSE SET cashback_get = 0; END IF; END;
MySQL INSERT INTO table SELECT FROM another_table, inside a PROCEDURE
I have this MySQL procedure, that makes some loops into 2 tables, prepares the Data into tblResults and then insert all data (if no errors) into a huge table after delete all rows found between 2 dates. The problem is that after the procedure finishes to run, I receive this warning: Unsafe statement written to the binary log using statement format since BINLOG_FORMAT = STATEMENT. Statements writing to a table with an auto-increment column after selecting from another table are unsafe because the order in which rows are retrieved determines what (if any) rows will be written. This order cannot be predicted and may differ on master and the slave. and as a result, if I have 250 distinct rows into tblResults table, the procedure insert 250 identical rows into final table. (usualy first or last row found in tblResults, multiplied by number of records from tblResults). The SQL code look like this: BEGIN -- DECLARE bDone INT; DECLARE CustomerId INT; DECLARE LocationId INT; DECLARE ContractId INT; DECLARE DatePeriod DATE; DECLARE SerialWeight DOUBLE; DECLARE Serial VARCHAR(150); DECLARE EnergyZone VARCHAR(5); DECLARE ConsDay DATE; DECLARE T0 DOUBLE; DECLARE T1 DOUBLE; DECLARE T2 DOUBLE; DECLARE T3 DOUBLE; DECLARE T4 DOUBLE; DECLARE T5 DOUBLE; DECLARE T6 DOUBLE; DECLARE T7 DOUBLE; DECLARE T8 DOUBLE; DECLARE T9 DOUBLE; DECLARE T10 DOUBLE; DECLARE T11 DOUBLE; DECLARE T12 DOUBLE; DECLARE T13 DOUBLE; DECLARE T14 DOUBLE; DECLARE T15 DOUBLE; DECLARE T16 DOUBLE; DECLARE T17 DOUBLE; DECLARE T18 DOUBLE; DECLARE T19 DOUBLE; DECLARE T20 DOUBLE; DECLARE T21 DOUBLE; DECLARE T22 DOUBLE; DECLARE T23 DOUBLE; DECLARE QtyEstimated DECIMAL(20,4); DECLARE QtyMeasured DECIMAL(20,4); DECLARE POD VARCHAR(50); DECLARE Quantity DECIMAL(20,4); DECLARE LocationCode VARCHAR(50); DECLARE rCustomerId INT; DECLARE rLocationId INT; DECLARE rContractId INT; DECLARE rDate DATE; DECLARE rTime INT; DECLARE rQtyEstimated DECIMAL(20,4); DECLARE rQtyPredicted DECIMAL(20,4); DECLARE rQtyMeasured DOUBLE; DECLARE rCreateUser INT; DECLARE rUpdateUser INT; DECLARE rFirmaId INT; DECLARE curs CURSOR FOR select ec.CustomerId, ec.LocationId, ec.Id as ContractId, els.Date as DatePeriod, els.SerialWeight, ets.Serial, ets.EnergyZone, ets.Date as ConsDay, ets.T0, ets.T1, ets.T2, ets.T3, ets.T4, ets.T5, ets.T6, ets.T7, ets.T8, ets.T9, ets.T10, ets.T11, ets.T12, ets.T13, ets.T14, ets.T15, ets.T16, ets.T17, ets.T18, ets.T19, ets.T20, ets.T21, ets.T22, ets.T23, CASE substr(els.Date, 6, 2) WHEN '01' THEN ec.Estimated1 WHEN '02' THEN ec.Estimated2 WHEN '03' THEN ec.Estimated3 WHEN '04' THEN ec.Estimated4 WHEN '05' THEN ec.Estimated5 WHEN '06' THEN ec.Estimated6 WHEN '07' THEN ec.Estimated7 WHEN '08' THEN ec.Estimated8 WHEN '09' THEN ec.Estimated9 WHEN '10' THEN ec.Estimated10 WHEN '11' THEN ec.Estimated11 WHEN '12' THEN ec.Estimated12 END as QtyEstimated from EnergyLocationSeries els left join EnergyTimeSeries ets ON ets.Serial = els.Serial and concat(substr(ets.Date, 1, 7), '-01') = els.Date left join EnergyLocation el ON el.Code2 = els.LocationCode left join EnergyContract ec ON (el.Id = ec.LocationId AND el.Codep = '') OR (ec.LocationId = (SELECT max(Id) FROM EnergyLocation WHERE Code2 = el.Codep) AND Codep !='') -- AND ec.`Status` != 'Reziliat' where els.Date = MTH and els.EnergyZone = ZONE order by ets.Date ASC LIMIT 10; DECLARE pods_cursor CURSOR FOR SELECT els.LocationCode, els.Quantity FROM EnergyLocation el RIGHT JOIN EnergyLocationSeries els ON els.LocationCode = el.Code2 OR els.LocationCode = el.Codep LEFT JOIN EnergyContract ec on ec.LocationId = el.Id WHERE el.Code2 IS NULL; DECLARE result CURSOR FOR SELECT `CustomerId`, `LocationId`, `ContractId`, `Date`, `Time`, `QtyEstimated`, `QtyPredicted`, `QtyMeasured`, `CreateUser`, `UpdateUser`, `FirmaId` FROM tblResults ORDER BY CustomerId, ContractId ASC; DROP TABLE IF EXISTS tblResultsErrors; CREATE TABLE IF NOT EXISTS tblResultsErrors ( `POD` INT(11) NULL DEFAULT NULL, `QtyMeasured` DECIMAL(20,4) NULL DEFAULT NULL ); DROP TABLE IF EXISTS tblResults; CREATE TABLE IF NOT EXISTS tblResults ( `CustomerId` INT(11) NULL DEFAULT NULL, `LocationId` INT(11) NULL DEFAULT NULL, `ContractId` INT(11) NULL DEFAULT NULL, `Date` DATE NULL DEFAULT NULL, `Time` SMALLINT(6) NULL DEFAULT NULL, `QtyEstimated` DECIMAL(20,4) NULL DEFAULT NULL, `QtyPredicted` DECIMAL(20,4) NULL DEFAULT NULL, `QtyMeasured` DOUBLE NULL DEFAULT NULL, `CreateUser` VARCHAR(32) NULL DEFAULT NULL, `UpdateUser` VARCHAR(32) NULL DEFAULT NULL, `FirmaId` INT(11) NULL DEFAULT NULL ); OPEN curs; BEGIN DECLARE bDone INT; DECLARE CONTINUE HANDLER FOR NOT FOUND SET bDone = 1; SET bDone = 0; REPEAT FETCH curs INTO CustomerId, LocationId, ContractId, DatePeriod, SerialWeight, Serial, EnergyZone, ConsDay, T0, T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12, T13, T14, T15, T16, T17, T18, T19, T20, T21, T22, T23, QtyEstimated; IF bDone = 0 THEN INSERT INTO tblResults VALUES (CustomerId,LocationId,ContractId,ConsDay,1,QtyEstimated,0,(T0 * (SerialWeight / 100)),'root','root',0), (CustomerId,LocationId,ContractId,ConsDay,2,QtyEstimated,0,(T1 * (SerialWeight / 100)),'root','root',0), (CustomerId,LocationId,ContractId,ConsDay,3,QtyEstimated,0,(T2 * (SerialWeight / 100)),'root','root',0), (CustomerId,LocationId,ContractId,ConsDay,4,QtyEstimated,0,(T3 * (SerialWeight / 100)),'root','root',0), (CustomerId,LocationId,ContractId,ConsDay,5,QtyEstimated,0,(T4 * (SerialWeight / 100)),'root','root',0), (CustomerId,LocationId,ContractId,ConsDay,6,QtyEstimated,0,(T5 * (SerialWeight / 100)),'root','root',0), (CustomerId,LocationId,ContractId,ConsDay,7,QtyEstimated,0,(T6 * (SerialWeight / 100)),'root','root',0), (CustomerId,LocationId,ContractId,ConsDay,8,QtyEstimated,0,(T7 * (SerialWeight / 100)),'root','root',0), (CustomerId,LocationId,ContractId,ConsDay,9,QtyEstimated,0,(T8 * (SerialWeight / 100)),'root','root',0), (CustomerId,LocationId,ContractId,ConsDay,10,QtyEstimated,0,(T9 * (SerialWeight / 100)),'root','root',0), (CustomerId,LocationId,ContractId,ConsDay,11,QtyEstimated,0,(T10 * (SerialWeight / 100)),'root','root',0), (CustomerId,LocationId,ContractId,ConsDay,12,QtyEstimated,0,(T11 * (SerialWeight / 100)),'root','root',0), (CustomerId,LocationId,ContractId,ConsDay,13,QtyEstimated,0,(T12 * (SerialWeight / 100)),'root','root',0), (CustomerId,LocationId,ContractId,ConsDay,14,QtyEstimated,0,(T13 * (SerialWeight / 100)),'root','root',0), (CustomerId,LocationId,ContractId,ConsDay,15,QtyEstimated,0,(T14 * (SerialWeight / 100)),'root','root',0), (CustomerId,LocationId,ContractId,ConsDay,16,QtyEstimated,0,(T15 * (SerialWeight / 100)),'root','root',0), (CustomerId,LocationId,ContractId,ConsDay,17,QtyEstimated,0,(T16 * (SerialWeight / 100)),'root','root',0), (CustomerId,LocationId,ContractId,ConsDay,18,QtyEstimated,0,(T17 * (SerialWeight / 100)),'root','root',0), (CustomerId,LocationId,ContractId,ConsDay,19,QtyEstimated,0,(T18 * (SerialWeight / 100)),'root','root',0), (CustomerId,LocationId,ContractId,ConsDay,20,QtyEstimated,0,(T19 * (SerialWeight / 100)),'root','root',0), (CustomerId,LocationId,ContractId,ConsDay,21,QtyEstimated,0,(T20 * (SerialWeight / 100)),'root','root',0), (CustomerId,LocationId,ContractId,ConsDay,22,QtyEstimated,0,(T21 * (SerialWeight / 100)),'root','root',0), (CustomerId,LocationId,ContractId,ConsDay,23,QtyEstimated,0,(T22 * (SerialWeight / 100)),'root','root',0), (CustomerId,LocationId,ContractId,ConsDay,24,QtyEstimated,0,(T23 * (SerialWeight / 100)),'root','root',0); END IF; UNTIL bDone END REPEAT; END; CLOSE curs; OPEN pods_cursor; BEGIN DECLARE bDone INT; DECLARE CONTINUE HANDLER FOR NOT FOUND SET bDone = 1; SET bDone = 0; REPEAT FETCH pods_cursor INTO POD, QtyMeasured; IF bDone = 0 THEN INSERT INTO tblResultsErrors VALUES (LocationCode, Quantity); END IF; UNTIL bDone END REPEAT; END; CLOSE pods_cursor; IF NOT EXISTS ( SELECT * FROM tblResultsErrors ) THEN BEGIN DELETE FROM EnergyIbdRecord WHERE Date BETWEEN MTH AND LAST_DAY(MTH); OPEN result; BEGIN DECLARE bDone INT; DECLARE CONTINUE HANDLER FOR NOT FOUND SET bDone = 1; SET bDone = 0; REPEAT FETCH result INTO rCustomerId,rLocationId,rContractId,rDate,rTime,rQtyEstimated,rQtyPredicted,rQtyMeasured,rCreateUser,rUpdateUser,rFirmaId; IF bDone = 0 THEN INSERT INTO EnergyIbdRecord (`CustomerId`, `LocationId`, `ContractId`, `Date`, `Time`, `QtyEstimated`, `QtyPredicted`, `QtyMeasured`, `CreateUser`, `UpdateUser`, `FirmaId`) VALUES (rCustomerId,rLocationId,rContractId,rDate,rTime,rQtyEstimated,rQtyPredicted,rQtyMeasured,rCreateUser,rUpdateUser,rFirmaId); END IF; UNTIL bDone END REPEAT; END; CLOSE result; END; ELSE BEGIN SELECT * FROM tblResultsErrors; END; END IF; END Any suggestion to get rid of inserting what tblResults contains? Maybe there is necessary to run 2 separated procedures? Would be this an approach?
Wherever possible, avoid using CURSORs. SQL is designed to do things in bulk, not one row at a time. Study constructs like INSERT INTO ... SELECT ...; CREATE TABLE ... SELECT ...; For example, pods_cursor can probably be eliminated via: INSERT INTO tblResultsErrors (POD, QtyMeasured) SELECT els.LocationCode, els.Quantity FROM EnergyLocation el RIGHT JOIN EnergyLocationSeries els ON els.LocationCode = el.Code2 OR els.LocationCode = el.Codep LEFT JOIN EnergyContract ec on ec.LocationId = el.Id WHERE el.Code2 IS NULL; (Ouch. Mixing RIGHT and LEFT makes my head spin like an owl's.) Using OR in ON sounds very inefficient. What is the intent?
Mysql group_concat limit rows in grouping
The next example is my database. tb_port id port 1 80 2 22 3 53 4 3128 5 443 tb_dest id dest 1 network 2 local tb_rule id id_port id_dest 1 1 1 2 2 1 3 3 1 4 4 1 5 5 1 Select: select dest,group_concat(port) from tb_port a, tb_dest b, tb_rule c where a.id=c.id_port and b.id=c.id_dest group by dest Result: network 80,22,53,3128,443 but is not the result I'm looking for, the result would be this. Select ex: select dest,group_concat(port limit 2) from tb_port a, tb_dest b, tb_rule c where a.id=c.id_port and b.id=c.id_dest group by dest result I would like network 80,22 network 53,3128 network 443 how to achieve this result only with SQL? Sqlfiddle: http://sqlfiddle.com/#!2/d11807
MySQL doesn't make this kind of query easy, but one (admittedly not very pretty) solution is to use a variable to give each row a sequence number per dest and just group by the row number integer divided by 2 to get two numbers in each group; SELECT dest, GROUP_CONCAT(port ORDER BY rank) ports FROM ( SELECT dest, port, ( CASE dest WHEN #curDest THEN #curRow := #curRow + 1 ELSE #curRow := 1 AND #curDest := dest END) rank FROM tb_port a JOIN tb_rule c ON a.id = c.id_port JOIN tb_dest b ON b.id = c.id_dest, (SELECT #curRow := 0, #curDest := '') r ORDER BY dest ) z GROUP BY FLOOR(rank/2),dest ORDER BY dest, MIN(rank) An SQLfiddle to test with.
Here is a stored proc,you just put in the delimiter when you call it DELIMITER $$ DROP PROCEDURE IF EXISTS explode_table $$ CREATE PROCEDURE explode_table(bound VARCHAR(255)) BEGIN DECLARE id TEXT; DECLARE value TEXT; DECLARE occurance INT DEFAULT 0; DECLARE i INT DEFAULT 0; DECLARE splitted_value TEXT; DECLARE done INT DEFAULT 0; DECLARE cur1 CURSOR FOR select dest,group_concat(port) from tb_port a, tb_dest b, tb_rule c where a.id=c.id_port and b.id=c.id_dest and dest != '' group by dest; DECLARE CONTINUE HANDLER FOR NOT FOUND SET done = 1; DROP TEMPORARY TABLE IF EXISTS table2; CREATE TEMPORARY TABLE table2( `id` VARCHAR(255), `value` VARCHAR(255) NOT NULL ) ENGINE=Memory; OPEN cur1; read_loop: LOOP FETCH cur1 INTO id, value; IF done THEN LEAVE read_loop; END IF; SET occurance = (SELECT LENGTH(CONCAT(value,bound)) - LENGTH(REPLACE(CONCAT(value,bound), bound, '')) +1); SET i=2; WHILE i <= occurance DO SET splitted_value = SUBSTRING_INDEX(SUBSTRING_INDEX(CONCAT(value,bound),bound,i),bound,-2) ; INSERT INTO table2 VALUES (id, splitted_value); SET i = i + 2; END WHILE; END LOOP; SELECT * FROM table2; CLOSE cur1; END; $$ CALL explode_table(',')
mysql - updating a table setting a column with a complex condition
I have been working on this for a while now and this seems to be too complex. What I want to do is to update a column (x) with the operation: (p * (100/c) ) / 100. p corresponds to a value of a date x and c corresponds to a value of date x minus one day. I tried to create a stored procedure with loop but select statement doesnt work for me in the loop statement. Here is my procedure which update nothing : BEGIN DECLARE firstqDate,date2 date; DECLARE p, c float; DECLARE cpt, val int; SET #val = 0; SET #cpt = (select count(*)-1 from quotes); WHILE (val < 3) DO SET #firstqDate = (select qDate from quotes ORDER BY YEAR(qDate) ASC, MONTH(qDate) ASC, DAY(qDate) ASC limit 1,1); SET date2 = (select qDate from quotes where qDate like DATE_ADD(#firstqDate, INTERVAL 1 DAY ); SET p = (select qOp from quotes where qDate like date2); SET c = (select qCl from quotes where qDate like DATE_SUB(date2, INTERVAL val DAY)); update quotes set qCh = (p * (100/c) ) / 100; set val = val + 1; end while; END EDIT : I did some updates to the stored procedure but still updating no lines! BEGIN DECLARE firstqDate,date2 date; DECLARE p, c float; DECLARE cpt, val int; SET #val = 0; SET #cpt = (select count(*)-1 from quotes); SET firstqDate = (select qDate from quotes ORDER BY YEAR(qDate) ASC, MONTH(qDate) ASC, DAY(qDate) ASC limit 1,1); WHILE (val < 3) DO SET date2 = (select qDate from quotes where qDate like DATE_ADD(#firstqDate, INTERVAL val DAY )); SET p = (select qOp from quotes where qDate like date2); SET c = (select qCl from quotes where qDate like DATE_SUB(date2, INTERVAL val+1 DAY)); set val = val + 1; update quotes set qCh = (p * (100/c) ) / 100 where qOp = p AND qCl = c; end while; END I did some updates again to the stored procedures but no changes. i used some functions. BEGIN DECLARE p, c float; DECLARE cpt, val int; SET #val = 0; SET #cpt = (select count(*)-1 from quotes); WHILE (#val < 3) DO SET p = getp(#val, getd()); SET c = getc(#val+1, getd()); set #val = #val + 1; update quotes set qCh = (#p * (100/#c) ) / 100 where qOp = #p AND qCl = #c; end while; END functions : get p: BEGIN declare d date; select qDate into d from quotes ORDER BY YEAR(qDate) ASC, MONTH(qDate) ASC, DAY(qDate) ASC limit 1,1; return d; END get c: BEGIN DECLARE c float; DECLARE qDa date; select qDate into qDa from quotes where qDate like DATE_SUB(qD, INTERVAL v DAY ); SELECT qCl INTO c FROM quotes WHERE qDate = qDa; RETURN c; END getd: BEGIN declare d date; select qDate into d from quotes ORDER BY YEAR(qDate) ASC, MONTH(qDate) ASC, DAY(qDate) ASC limit 1,1; return d; END this stored procedure must calculate all qCh from p of qDate and c of the qDate minus one day. Thank you! EDIT - Solved Ouf! I finally managed to write this stored procedure : BEGIN DECLARE p, c float; DECLARE cpt, val int; SET #val = 0; SET #cpt = (select count(*)-1 from quotes); WHILE (#val <= 2) DO SET p := getp(#val, getd()); SET c := getc(#val+1, getd()); set #val := #val + 1; update quotes q set q.qCh = (getp(#val, getd()) * (100/getc(#val-1, getd())) ) / 100 where q.qOp = getp(#val, getd()); end while; END new getC BEGIN DECLARE c float; DECLARE qDa date; select qDate into qDa from quotes where qDate like DATE_ADD(qD, INTERVAL v DAY ); SELECT qCl INTO c FROM quotes WHERE qDate = qDa; RETURN c; END I changed the code of function getC to add (-1) in the first iteration. now it is working! Thank you everyone for your help!
Your update cycle looks ok, even if i don't understand why you make 3 cycles. Shouldn't you use: WHILE (#val < 3) DO Instead of WHILE (val < 3) DO ? Hope it helps EDIT: You need to debug your cycle to know where the problem is. Try this: BEGIN DECLARE #p, #c float; DECLARE #cpt, #val int; SET #val = 0; SET #cpt = (select count(*)-1 from quotes); SELECT 'Enter Cycle'; WHILE (#val < 3) DO SELECT 'In Cyle'; SET #p = getp(#val, getd()); SELECT #p; SET c = getc(#val+1, getd()); set #val = #val + 1; update quotes set qCh = (#p * (100/#c) ) / 100 where qOp = #p AND qCl = #c; end while; END Does you SP prints 'Enter Cycle' and 'In Cyle'? Does the value of p Variable prints? It is correct?
Cursor in stored procedure of mysql not working
I am using following stored procedure and calling a cursor inside it but it is returning me zero data fetched or processed what is wrong in the procedure ? DELIMITER $$ CREATE DEFINER=`root`#`localhost` PROCEDURE `sp_ProcessData`( DummyDate datetime ) BEGIN DECLARE MONTH BIGINT; DECLARE YEAR BIGINT; declare LBrCode VARCHAR(100); declare EntryDate datetime; declare VcrAcctId char(32); declare DrCr VARCHAR(100); declare FcyTrnAmt VARCHAR(100); DECLARE CustName char(50); DECLARE CreditAmount decimal(18,2); DECLARE DebitAmount decimal(18,2); DECLARE BatchCd char(15); DECLARE SetNo BIGINT; DECLARE ScrollNo BIGINT; DECLARE BookType char(10); DECLARE ActualAcctId varchar(50); DECLARE ActualBrCode varchar(50); DECLARE ActualBookType varchar(50); declare curProcessAMLData cursor for select distinct * from DummyTable WHERE EntryDate = DummyDate AND (ActualBookType = 'XX'); open curProcessAMLData; fetch next from curProcessAMLData into LBrCode,EntryDate,VcrAcctId,DrCr,FcyTrnAmt,BatchCd,SetNo,ScrollNo,BookType,ActualAcctId,ActualBrCode,ActualBookType; while fetch_status = 0 DO SET MONTH = MONTH(DummyDate); SET YEAR = MONTH(DummyDate); IF(DrCr = 'C') THEN SET CreditAmount = FcyTrnAmt; IF NOT EXISTS (SELECT * FROM Master WHERE BranchCode = ActualBrCode AND AccNo = ActualAcctId AND TransMonth = MONTH and TransYear = YEAR) THEN INSERT INTO Master ( TransDate, BranchCode, AccNo, Credit, TransMonth, TransYear ) SELECT EntryDate, ActualBrCode, ActualAcctId, CreditAmount, MONTH, YEAR END; ELSE UPDATE Master SET Credit = IFNULL(Credit,0) + CreditAmount WHERE BranchCode = ActualBrCode AND AccNo = ActualAcctId AND MONTH(TransDate) = MONTH AND YEAR(TransDate) = YEAR; END IF; ELSE SET DebitAmount = FcyTrnAmt; IF NOT EXISTS (SELECT * FROM Master WHERE BranchCode = ActualBrCode AND AccNo = ActualAcctId AND TransMonth = MONTH and TransYear = YEAR) THEN INSERT INTO Master ( TransDate, BranchCode, AccNo, Debit, TransMonth, TransYear ) SELECT EntryDate, ActualBrCode, ActualAcctId, DebitAmount, MONTH, YEAR END; ELSE UPDATE Master SET Debit = IFNULL(Debit,0) + DebitAmount WHERE BranchCode = #ActualBrCode AND AccNo = ActualAcctId AND MONTH(TransDate) = MONTH AND YEAR(TransDate) = YEAR; END IF; END IF; SET FcyTrnAmt = 0 ; END WHILE; fetch next from curProcessAMLData into LBrCode,EntryDate,VcrAcctId,DrCr,FcyTrnAmt,BatchCd,SetNo,ScrollNo,BookType,ActualAcctId,ActualBrCode,ActualBookType; CLOSE curProcessAMLData; END What changes will i have to make to make it working ?