Converting Oracle SQL Procedure into MySQL Stored Procedure - mysql

I am trying to convert a complex oracle sql procedure to mysql. The procedure contains of many differenct selects, cursors etc. I already wrote a version of it in mysql, but it does not work and only gives some error messages. I hope on could help me.
Tables
CREATE TABLE IF NOT EXISTS `NutritionalInformation`
(
`idNuIn` INT NOT NULL PRIMARY KEY AUTO_INCREMENT,
`calories` FLOAT NULL,
`saturatedFat` FLOAT NULL,
`transFat` FLOAT NULL,
`carbohydrates` FLOAT NULL,
`sugar` FLOAT NULL,
`protein` FLOAT NULL,
`salt` FLOAT NULL
);
CREATE TABLE IF NOT EXISTS `Inventory`
(
`idInventory` INT NOT NULL,
`idIngredient` INT NOT NULL,
`idStore` INT NOT NULL,
`expiryDate` DATE NULL,
`deliveryDate` DATE NOT NULL,
`amount` INT NOT NULL,
`isAccessible` INT NOT NULL,
CONSTRAINT `fk_Inventory_Ingredient`
FOREIGN KEY (`idIngredient`)
REFERENCES `Ingredient` (`idIngredient`),
CONSTRAINT `fk_Inventory_StoreA`
FOREIGN KEY (`idStore`)
REFERENCES `WaffleStore` (`idStore`),
CONSTRAINT pk_Inventory
PRIMARY KEY (idInventory)
);
CREATE TABLE IF NOT EXISTS `Inventory`
(
`idInventory` INT NOT NULL,
`idIngredient` INT NOT NULL,
`idStore` INT NOT NULL,
`expiryDate` DATE NULL,
`deliveryDate` DATE NOT NULL,
`amount` INT NOT NULL,
`isAccessible` INT NOT NULL,
PRIMARY KEY (`idIngredient`, `idStore`),
CONSTRAINT `fk_Inventory_Ingredient`
FOREIGN KEY (`idIngredient`)
REFERENCES `Ingredient` (`idIngredient`),
CONSTRAINT `fk_Inventory_StoreA`
FOREIGN KEY (`idStore`)
REFERENCES `WaffleStore` (`idStore`)
);
CREATE TABLE IF NOT EXISTS `Product`
(
`idProduct` INT NOT NULL PRIMARY KEY AUTO_INCREMENT,
`idNuIn` INT NOT NULL,
`price` FLOAT NOT NULL,
`name` VARCHAR(255) NOT NULL,
CONSTRAINT `fk_Product_NutritionalInformation1`
FOREIGN KEY (`idNuIn`)
REFERENCES `NutritionalInformation` (`idNuIn`)
);
CREATE TABLE IF NOT EXISTS `Waffle`
(
`idWaffle` INT NOT NULL PRIMARY KEY AUTO_INCREMENT,
`creatorName` VARCHAR(255) NULL,
`creationDate` DATE NOT NULL,
`processingTimeSec` INT,
`healty` VARCHAR(255),
CONSTRAINT `fk_Waffle_Product1`
FOREIGN KEY (`idWaffle`)
REFERENCES `Product` (`idProduct`)
);
CREATE TABLE IF NOT EXISTS `WaffleIngredient`
(
`idIngredient` INT NOT NULL,
`idWaffle` INT NOT NULL,
`amount` INT NOT NULL,
PRIMARY KEY (`idIngredient`, `idWaffle`),
CONSTRAINT `fk_WaffleRecept_Ingredient1`
FOREIGN KEY (`idIngredient`)
REFERENCES `Ingredient` (`idIngredient`),
CONSTRAINT `fk_WaffleRecept_Waffle1`
FOREIGN KEY (`idWaffle`)
REFERENCES `Waffle` (`idWaffle`)
);
CREATE TABLE IF NOT EXISTS `WaffleStore`
(
`idStore` INT NOT NULL PRIMARY KEY AUTO_INCREMENT,
`name` VARCHAR(255) NULL,
`areaCode` VARCHAR(15) NULL,
`location` VARCHAR(255) NULL,
`streetName` VARCHAR(255) NULL,
`houseNumber` VARCHAR(45) NULL
);
Example Inserts
INSERT INTO NutritionalInformation (idNuIn, calories, saturatedFat, transFat, carbohydrates, sugar, protein, salt)
VALUES (4, 60, 0, 0, 0, 0, 0, 0);
INSERT INTO NutritionalInformation (idNuIn, calories, saturatedFat, transFat, carbohydrates, sugar, protein, salt)
VALUES (5, 350, 3, 3, 5, 5, 3, 1);
INSERT INTO INGREDIENT (idIngredient, idNuIn, name, unit, price, processingTimeSec)
VALUES (3, 4, 'Apfel', 'g', 0.5, 3);
INSERT INTO PRODUCT (idProduct, idNuIn, price, name)
VALUES (4, 5, 3.5, 'ApfelWaffel');
INSERT INTO WAFFLE (idWaffle, creatorName, creationDate, processingTimeSec, healty)
VALUES (4, 'Berndt', '2020-12-01', NULL, NULL);
INSERT INTO WAFFLEINGREDIENT(idIngredient, idWaffle, amount)
VALUES (3, 4, 2);
INSERT INTO WaffleStore (idStore, name, areaCode, location, streetName, houseNumber)
VALUES (1, 'Waffle GMBH', '50000', 'TEST', 'TEST', '38');
INSERT INTO INVENTORY(idInventory, idIngredient, idStore, expiryDate, deliveryDate, amount, isAccessible)
VALUES (2, 3, 1, '3032-12-30', '3032-12-30', 100, 1);
INSERT INTO WaffleOrder(idOrder, idStore, totalAmount, paymentStatus, orderDate)
VALUES (1, 1, 2, 0, '2020-12-30');
Oracle SQL PROCEDURE
CREATE OR REPLACE PROCEDURE OnInventoryAdd (
s_idProduct IN INT,
s_idOrder IN INT,
s_extenal_amount IN INT
)
IS
v_store INT;
v_waffle_id INT;
v_cursor_ingredientid INT;
v_cursor_amount INT;
v_cursor_expiryDate DATE;
v_cursor_deliveryDate DATE;
v_operator VARCHAR(3) := 'add';
CURSOR v_Ingredient_Cursor_On_Insert(w_Id INT) IS
SELECT idIngredient, amount FROM WAFFLEINGREDIENT WHERE idWaffle = w_Id;
CURSOR v_Ingredient_Cursor_On_Delete(i_id INT) IS
SELECT expiryDate, deliveryDate FROM Inventory WHERE idIngredient = i_id;
BEGIN
SELECT idStore INTO v_store FROM WAFFLEORDER WHERE idOrder = s_idOrder;
SELECT w.idWaffle INTO v_waffle_id FROM Waffle w WHERE w.idProduct = s_idProduct;
-- If more than one waffle is bought
FOR x IN 1..s_extenal_amount LOOP
-- Get all ingredient information of waffle
OPEN v_Ingredient_Cursor_On_Insert(v_waffle_id);
LOOP
FETCH v_Ingredient_Cursor_On_Insert INTO v_cursor_ingredientId, v_cursor_amount;
EXIT WHEN v_Ingredient_Cursor_On_Insert%NOTFOUND;
-- Get all old expirydate and deliverydate information
OPEN v_Ingredient_Cursor_On_Delete(v_cursor_ingredientId);
LOOP
FETCH v_Ingredient_Cursor_On_Delete INTO v_cursor_expiryDate, v_cursor_deliveryDate;
EXIT WHEN v_Ingredient_Cursor_On_Delete%NOTFOUND;
END LOOP;
CLOSE v_Ingredient_Cursor_On_Delete;
END LOOP;
CLOSE v_Ingredient_Cursor_On_Insert;
-- Update the Inventory
InventoryUpdate(v_store, v_cursor_ingredientId, v_cursor_amount, v_operator, v_cursor_expiryDate, v_cursor_deliveryDate);
END LOOP;
END;
/
Current Version
DROP PROCEDURE IF EXISTS `OnInventoryAdd`;
DELIMITER //
CREATE PROCEDURE `OnInventoryAdd` (
s_idProduct INT,
s_idOrder INT,
s_extenal_amount INT
)
BEGIN
DECLARE loop_counter INT DEFAULT s_extenal_amount;
DECLARE v_store INT;
DECLARE v_waffle_id INT;
DECLARE v_cursor_ingredientid INT;
DECLARE v_cursor_amount INT;
DECLARE v_cursor_expiryDate DATE;
DECLARE v_cursor_deliveryDate DATE;
DECLARE v_operator VARCHAR(3) DEFAULT 'add';
DECLARE v_c_insert_done, v_c_delete_done BOOLEAN DEFAULT FALSE;
DECLARE v_Ingredient_Cursor_On_Insert CURSOR FOR
SELECT idIngredient, amount FROM WAFFLEINGREDIENT WHERE idWaffle = v_waffle_id;
DECLARE CONTINUE HANDLER FOR NOT FOUND SET v_c_insert_done = TRUE;
SELECT idStore INTO v_store FROM WAFFLEORDER WHERE idOrder = s_idOrder;
SELECT idWaffle INTO v_waffle_id FROM Waffle WHERE idWaffle = s_idProduct;
WHILE loop_counter > 0 DO
SET loop_counter = loop_counter - 1;
OPEN v_Ingredient_Cursor_On_Insert;
curr_insert_loop: LOOP
FETCH FROM v_Ingredient_Cursor_On_Insert INTO v_cursor_ingredientId, v_cursor_amount;
IF v_c_insert_done THEN
CLOSE v_Ingredient_Cursor_On_Insert;
LEAVE curr_insert_loop;
END IF;
BLOCK2 : BEGIN
DECLARE v_Ingredient_Cursor_On_Delete CURSOR FOR
SELECT expiryDate, deliveryDate FROM Inventory WHERE idIngredient = v_cursor_ingredientid;
DECLARE CONTINUE HANDLER FOR NOT FOUND SET v_c_delete_done = TRUE;
OPEN v_Ingredient_Cursor_On_Delete;
curr_delete_loop : LOOP
FETCH FROM v_Ingredient_Cursor_On_Delete INTO v_cursor_expiryDate, v_cursor_deliveryDate;
IF v_c_delete_done THEN
CLOSE v_Ingredient_Cursor_On_Delete;
LEAVE curr_delete_loop;
END IF;
END LOOP curr_delete_loop;
END BLOCK2;
END LOOP curr_insert_loop;
CALL InventoryUpdate(v_store, v_cursor_ingredientId, v_cursor_amount, v_operator, v_cursor_expiryDate, v_cursor_deliveryDate);
END WHILE;
END //
DELIMITER ;
Error
4 row(s) affected, 2 warning(s): 1264 Out of range value for column 'expiryDateOnInsert' at row 2 1264 Out of range value for column 'deliveryDateOnInsert' at row 1
Even tho I wrote the Oracle Procedure, I have zero clue how to write the same behavior in MYSQL and more over how to fix this error. If there is a alternative to do the same without cursors, then it would be fine too

Ok, I've managed to convert the oracle procedure into mysql stored procedure, here is the working code:
Code
CREATE PROCEDURE `OnInventoryAdd` (
s_idProduct INT,
s_idOrder INT,
s_extenal_amount INT
)
BEGIN
DECLARE loop_counter INT DEFAULT s_extenal_amount;
DECLARE done1, done2 BOOLEAN DEFAULT FALSE;
DECLARE v_store INT;
DECLARE v_waffle_id INT;
DECLARE v_operator VARCHAR(3) DEFAULT 'add';
DECLARE v_cursor_ingredientid INT;
DECLARE v_cursor_amount INT;
DECLARE v_cursor_expiryDate DATE;
DECLARE v_cursor_deliveryDate DATE;
DECLARE v_Ingredient_Cursor_On_Insert CURSOR FOR
SELECT idIngredient, amount FROM WAFFLEINGREDIENT WHERE idWaffle = v_waffle_id;
DECLARE CONTINUE HANDLER FOR NOT FOUND SET done1 = TRUE;
SELECT idStore INTO v_store FROM WAFFLEORDER WHERE idOrder = s_idOrder;
SELECT idWaffle INTO v_waffle_id FROM Waffle WHERE idWaffle = s_idProduct;
REPEAT
OPEN v_Ingredient_Cursor_On_Insert;
loop1 : LOOP
FETCH FROM v_Ingredient_Cursor_On_Insert INTO v_cursor_ingredientId, v_cursor_amount;
IF done1 THEN
CLOSE v_Ingredient_Cursor_On_Insert;
LEAVE loop1;
END IF;
BLOCK1 : BEGIN
DECLARE v_Ingredient_Cursor_On_Delete CURSOR FOR
SELECT expiryDate, deliveryDate FROM Inventory WHERE idIngredient = v_cursor_ingredientid;
DECLARE CONTINUE HANDLER FOR NOT FOUND SET done2 = TRUE;
OPEN v_Ingredient_Cursor_On_Delete;
loop2 : LOOP
FETCH FROM v_Ingredient_Cursor_On_Delete INTO v_cursor_expiryDate, v_cursor_deliveryDate;
IF done2 THEN
SET done2 = FALSE; -- This was the solution
LEAVE loop2;
END IF;
END LOOP loop2;
END BLOCK1;
END LOOP loop1;
CALL InventoryUpdate(v_store, v_cursor_ingredientId, v_cursor_amount, v_operator, v_cursor_expiryDate, v_cursor_deliveryDate);
SET loop_counter = loop_counter - 1;
UNTIL loop_counter = 0
END REPEAT;
END //
DELIMITER ;

Related

how to have insertion happen only once in a cursor loop in mysql

This procedure takes a brand name and matches it with the brandnames in the product table and creates a campaign.
When I call this procedure BrandNameCampaign with an input of a brandname that does NOT exist in the product table it is still creating a campaign. I know it's because I have kept the insertion query outside of the loop where it is checking whether camp_c cursor has null values or not.
However, if I put the query inside the repeat loop of the cursor, it generates an error code: 1062 duplicate entry 'x' (x being an int) for key 'campaign.PRIMARY'.
How do I fix my code so that a new campaign does not get inserted into the table without creating/firing a trigger. I want it to work within this procedure.
Table code
create table Product (
ProductID int not null,
ProductType varchar (20) not null,
PackageType varchar(20) not null,
YearProduced int not null,
Price float not null,
Brand varchar(255) not null,
PRIMARY KEY (ProductID)
)
create table Campaign (
CampaignID int not null,
CampaignStartDate date not null,
CampaignEndDate date,
PRIMARY KEY (CampaignID)
)
create table DiscountDetails (
ProductID int not null,
CampaignID int not null,
MembershipLevel varchar(20) not null,
Discount int not null,
primary key (ProductID, CampaignID, MembershipLevel),
foreign key (ProductID) references Product (ProductID),
foreign key (CampaignID) references Campaign (CampaignID)
)
Procedure code
create procedure BrandNameCampaign (in brandname varchar(50))
begin
declare v_finished int default 0;
declare prod_id int;
declare newcampid int;
declare camp_brand varchar(255);
declare camp_c cursor for
select productid, brand
from product
where brandname = brand
order by price desc limit 5;
declare continue handler for not found set v_finished = 1;
SELECT
MAX(CampaignID)
INTO newcampid FROM
campaign;
set newcampid = 1 + newcampid;
insert into `Campaign`(`CampaignID`,`CampaignStartDate`,`CampaignEndDate`) values
(newcampid,date_add(curdate(), interval 4 week), date_add( curdate(), interval 8 week));
-- working with cursor
open camp_c;
repeat
fetch camp_c into prod_id, camp_brand;
if not (v_finished = 1) then
insert into discountdetails values (prod_id, newcampid, 'S', 20);
insert into discountdetails values (prod_id, newcampid, 'G', 30);
insert into discountdetails values (prod_id, newcampid, 'P', 40);
end if;
until v_finished
end repeat;
close camp_c;
end//
One solution would be to use:
insert ignore into `Campaign` ...
The ignore means do not generate an error if the insert results in a duplicate key or other type of error.
A different solution might be to use a boolean variable:
declare v_do_insert tinyint(1) default true;
...
repeat
insert into `Campaign`(`CampaignID`,`CampaignStartDate`,`CampaignEndDate`)
select newcampid, date_add(curdate(), interval 4 week), date_add( curdate(), interval 8 week)
from dual where v_do_insert=true;
set v_do_insert = false;
...
until v_finished
end repeat;
In this example, the insert...select would insert one row the first time through the loop, but then on subsequent iterations of the loop, v_do_insert is now false, so the insert...select would insert zero rows.

Column count doesn't match with the value count in row 1

I am trying to populate a mqsql table with random values. I created a stored procedure for this but it gives me the error "column count doesn't match with the value count in row 1" when I execute it.
Below is what I have tried
The stored procedure
CREATE DEFINER=`root`#`localhost` PROCEDURE `GenerateManagerData`()
BEGIN
DECLARE i INT DEFAULT 1;
WHILE i <= 100 DO
INSERT INTO projectManager(id,name,email,contact_number) VALUES (i+ 'M', CAST(i AS CHAR(10)), 'e'+ CAST(i AS CHAR(10))+ '#gmail.com', 'TP' + CAST(i AS CHAR(10)));
SET i = i + 1;
END WHILE;
END
This is the table I have created
CREATE TABLE `projectmanager` (
`id` int(10) NOT NULL AUTO_INCREMENT,
`name` varchar(100) DEFAULT NULL,
`email` varchar(100) DEFAULT NULL,
`contact_number` varchar(20) DEFAULT NULL,
PRIMARY KEY (`id`),
UNIQUE KEY `email_UNIQUE` (`email`)
);
I have given all the columns in the stored procedure. Please help me with this.
It was an issue with the CAST funation. Using CONCAT() fixed the issue,
CREATE DEFINER=`root`#`localhost` PROCEDURE `GenerateManagerData`()
BEGIN
DECLARE i INT DEFAULT 38;
WHILE i <= 100 DO
INSERT INTO projectManager(name,email,contact_number) VALUES (CONCAT('M', i), CONCAT('e', i, '#gmail.com'), CONCAT('TP', i));
SET i = i + 1;
END WHILE;
END

my procedure with cursor in mysql

I have a problem and I don't know how to solve it.
I need to create a procedure with cursor to insert into Vizite: dataora (i need a function), Medici_Idm,Pacienti_Idm,Cabinete_Idm from temporary table.My procedure doesn't work, i also use for select tables: Medici, Pacineti,Cabinete to extract id.
Table 1:
CREATE TABLE IF NOT EXISTS Vizite (
Idv INT NOT NULL AUTO_INCREMENT PRIMARY KEY,
DataOra DATETIME,
Medici_Idm INT NOT NULL,
Pacienti_Idp INT NOT NULL,
Cabinete_Idc INT NOT NULL,
FOREIGN KEY (Medici_Idm) REFERENCES Medici(Idm),
FOREIGN KEY (Pacienti_Idp) REFERENCES Pacienti(Idp),
FOREIGN KEY (Cabinete_Idc) REFERENCES Cabinete(Idc)
) Engine=INNODB;
Table 2:
CREATE TEMPORARY TABLE IF NOT EXISTS TempVizite (
Idt INT NOT NULL AUTO_INCREMENT PRIMARY KEY,
DataVizita VARCHAR(250),
OraIntrare TIME,
NumePacient VARCHAR(250),
PrenumePacient VARCHAR(250),
NumeMedic VARCHAR(250),
PrenumeMedic VARCHAR(250),
Cabinet VARCHAR (250));
the procedure:
DELIMITER /
CREATE PROCEDURE VARIANTA3()
BEGIN
DECLARE M_I,P_I,C_I VARCHAR(100);
DECLARE I_V INT;
DECLARE D DATE;
DECLARE O TIME;
DECLARE CURS1 CURSOR FOR -- declaram cursorul
SELECT IDT,DATAVIZITA,ORAINTRARE,NUMEMEDIC,NUMEPACIENT,CABINET FROM TEMPVIZITE;
DECLARE EXIT HANDLER FOR 1329 BEGIN END; -- declaram handler specific erorii de terminarea cursorului
OPEN CURS1;
BUCLA: LOOP
FETCH CURS1 INTO M_I,P_I,C_I,I_V,D,O;
INSERT IGNORE INTO VIZITE VALUES(I_V,#DATAORA,M_I,P_I,C_I);
SELECT TIMESTAMP(DATAVIZITA,ORAINTRARE) INTO #DATAORA;
SELECT IDM FROM MEDICI WHERE NUME = NUMEMEDIC INTO M_I;
SELECT IDP FROM PACIENTI WHERE NUME = NUMEPACIENT INTO P_I;
SELECT IDC FROM CABINETE WHERE NUME = CABIENT INTO C_I;
END LOOP;
CLOSE CURS1;
END /
DELIMITER ;

Error Code: 1062 Duplicate entry for key 'PRIMARY'

I am constantly getting a Error code 1062: Duplicate Entry.
The first row insert, but then it fails on the same ID.
So everytime I hit execute it will increment: 1466, 1467, 1468, 1469.
And each time there is the same record entered, so I am assuming the autoincrement is only working for the first iteration.
Table:
'entity':
CREATE TABLE `entity` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`name` varchar(255) NOT NULL,
`reg_num` varchar(45) NOT NULL,
`enterprise_id` int(11) DEFAULT NULL,
PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=1474 DEFAULT CHARSET=latin1 COMMENT=\'Comment'
Stored procedure:
DELIMITER $$
CREATE DEFINER=`root`#`localhost` PROCEDURE `tp_to_entityPROC`()
DETERMINISTIC
COMMENT 'stored'
BEGIN
DECLARE done BOOLEAN DEFAULT 0;
DECLARE Tid INT;
DECLARE Tt_name TEXT;
DECLARE allt CURSOR FOR
SELECT training_provider_id, training_provider_name
FROM training_providers;
DECLARE CONTINUE HANDLER FOR NOT FOUND SET done=1;
OPEN allt;
read_loop: LOOP
IF done THEN
LEAVE read_loop;
END IF;
FETCH allt INTO Tid, Tt_name;
SET #id = 0;
SET #t_name = 0;
SET #id = Tid;
SET #t_name = Tt_name;
SET #empty = '';
if (#id != 0) THEN
INSERT INTO entity (name)
VALUES (#t_name);
SET #my_id = LAST_INSERT_ID();
IF #my_id != 0 THEN
UPDATE training_awarded_providers
SET training_awarded_provider_id = #my_id
WHERE training_awarded_provider_id = #id;
END IF;
END IF;
END LOOP;
CLOSE allt;
END
Not sure about the exact error of duplicate entry but your posted code is not going to work.
Your Table schema
CREATE TABLE `entity` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`name` varchar(255) NOT NULL,
`reg_num` varchar(45) NOT NULL <-- Here it's non null column
In your store procedure you are trying to insert null to reg_num column which will never succeed
if (#id != 0) THEN
INSERT INTO entity (name)
VALUES (#t_name);

mySQL Stored Procedure - Cursor error

I'm trying to write a mySQL procedure with a cursor to calculate a fare. I pass in the stationid's then I figure out what zone they are in. The fare is a set value of $1 and an additional $0.20 for each zone traveled in.
The code I have so far runs but there is a problem with the cursor not fetching the values into the variables.
Any help would be greatly appreciated. Thanks
Tables:
DROP DATABASE IF EXISTS luasSystem;
CREATE DATABASE luasSystem;
USE luasSystem;
CREATE TABLE IF NOT EXISTS line
(
line_id INT NOT NULL AUTO_INCREMENT,
Line_colour CHAR(10) NOT NULL,
PRIMARY KEY (line_id)
) ENGINE=InnoDB;
CREATE TABLE IF NOT EXISTS zone
(
zone_id INT NOT NULL AUTO_INCREMENT,
zone_name VARCHAR(20) NOT NULL,
line INT NOT NULL,
PRIMARY KEY (zone_id),
FOREIGN KEY (line) REFERENCES line(line_id) ON UPDATE CASCADE ON DELETE RESTRICT
) ENGINE=InnoDB;
CREATE TABLE IF NOT EXISTS station
(
station_id INT NOT NULL AUTO_INCREMENT,
station_name CHAR(20) NOT NULL,
service CHAR(20),
line INT NOT NULL,
zone INT NOT NULL,
PRIMARY KEY (station_id),
FOREIGN KEY (line) REFERENCES line(line_id) ON UPDATE CASCADE ON DELETE RESTRICT,
FOREIGN KEY (zone) REFERENCES zone(zone_id) ON UPDATE CASCADE ON DELETE RESTRICT
) ENGINE=InnoDB;
Stored Procedure:
DROP PROCEDURE IF EXISTS calculateFare;
DELIMITER //
CREATE PROCEDURE calculateFare
(
IN stationid1 INT, IN stationid2 INT
)
BEGIN
DECLARE zoneNum1 INT;
DECLARE zoneNum2 INT;
DECLARE num INT;
DECLARE fare DOUBLE;
DECLARE tableEnd BOOLEAN;
DECLARE zoneCur CURSOR FOR
SELECT zone, zone FROM station
WHERE station_name = stationid1 AND station_name = stationid2;
DECLARE CONTINUE HANDLER FOR NOT FOUND
SET tableEnd = TRUE;
OPEN zoneCur;
the_loop: LOOP
FETCH zoneCur
INTO zoneNum1, zoneNum2;
IF tableEnd THEN
CLOSE zoneCur;
LEAVE the_loop;
END IF;
SET fare = 1;
SET num = 0;
IF zoneNum1 < zoneNum2 THEN
SET num = zoneNum2 - zoneNum1;
ELSEIF zoneNum1 > zoneNum2 THEN
SET num = zoneNum1 - zoneNum2;
END IF;
SET fare = (num * 0.20) + 1;
SELECT fare;
END LOOP the_loop;
END //
DELIMITER ;
CAll calculateFare(3,5);
Wouldn't this be easier of you used decimal values instead of integers? Suggest you look at : http://dev.mysql.com/doc/refman/5.0/en/fixed-point-types.html