Case not working for my stored procedure - mysql

I have created this procedure to insert upc_id and relevent values in the table product_universal_description.
CREATE PROCEDURE veealpha
(
IN s_po_id INT(11),
IN s_supplier_id INT(11),
IN s_location_id VARCHAR(32),
IN s_warehouse_id INT(11),
IN s_user_id INT(11),
OUT message VARCHAR(64),
OUT error_code INT(4)
)
BEGIN
DECLARE temp_upc VARCHAR(32);
DECLARE i INT;
DECLARE finished INTEGER DEFAULT 0;
DECLARE loop_count int(4);
DECLARE upc varchar(32);
DECLARE p_product_id int(11);
DECLARE p_model varchar(64);
DECLARE counter_cursor CURSOR FOR
SELECT product_id,model,quantity FROM product
WHERE model in('CFB0040','CFB0042','CFB0043','CFB0044')
AND quantity > 0;
DECLARE CONTINUE HANDLER FOR 1062
SET message = 'Duplicate Keys Found';
DECLARE CONTINUE HANDLER FOR NOT FOUND
SET finished = 1;
OPEN counter_cursor;
add_data : LOOP
FETCH counter_cursor INTO p_product_id, p_model, loop_count;
SET i = 1;
WHILE loop_count > 0 DO
CASE i
WHEN i < 10 THEN
SET temp_upc = CONCAT(s_po_id,'-','CFC','-','30','-','APR14','-',p_model,'-000',i);
WHEN (i >= 10 AND i < 100) THEN
SET temp_upc = CONCAT(s_po_id,'-','CFC','-','30','-','APR14','-',p_model,'-00',i);
WHEN (i >= 100 AND i < 1000) THEN
SET temp_upc = CONCAT(s_po_id,'-','CFC','-','30','-','APR14','-',p_model,'-0',i);
ELSE
SET temp_upc = CONCAT(s_po_id,'-','CFC','-','30','-','APR14','-',p_model,'-',i);
END CASE;
INSERT INTO product_universal_description
(
`upc_id`,
`po_id`,
`supplier_id`,
`location_id`,
`warehouse_id`,
`product_id`,
`model_no`,
`added_by`,
`updated_by`,
`date_added`,
`date_modified`
) VALUES (
temp_upc,
s_po_id,
s_supplier_id,
s_location_id,
s_warehouse_id,
p_product_id,
p_model,
s_user_id,
s_user_id,
NOW(),
NOW()
);
SET i=i+1;
SET loop_count = loop_count - 1;
END WHILE;
IF finished = 1 THEN
LEAVE add_data;
END IF;
END LOOP add_data;
CLOSE counter_cursor;
END
CALL veealpha(123,45,'UP',1,56,#msg,#err);
ON Execution I getting the result like this.
How ever I have given the conditions there for UPC_ID that it should be well mannered as per case. But leaving for i = 1 FOR all it takes the ELSE condition at CASE. Can anybody tell me .. what's wrong happened and how could i get the desired result.

Try:
...
-- CASE i
CASE
WHEN i < 10 THEN
SET temp_upc = CONCAT(s_po_id,'-','CFC','-','30','-','APR14','-',p_model,'-000',i);
WHEN (i >= 10 AND i < 100) THEN
SET temp_upc = CONCAT(s_po_id,'-','CFC','-','30','-','APR14','-',p_model,'-00',i);
WHEN (i >= 100 AND i < 1000) THEN
SET temp_upc = CONCAT(s_po_id,'-','CFC','-','30','-','APR14','-',p_model,'-0',i);
ELSE
SET temp_upc = CONCAT(s_po_id,'-','CFC','-','30','-','APR14','-',p_model,'-',i);
END CASE;
...

Related

How do I fetch the data using multiple cursors and multiple loops in MySQL Stored Procedure?

As per the use case, this procedure should return 30 rows with 15 unique lead id's corresponding to all 15 in activity=1; randomly 10 participate in activity = 2; and from those 10, 5 leads randomly correspond to activity=3.
When I run the stored procedure, it goes on until populating 25 records; which correspond to uniquely getting 15 id's for activity=1 and 10 out of them for activity=2; but, I am unable to fetch the records right after.
If you check down in the code; I have mentioned a SELECT statement just before closing cur2 (SELECT COUNT(*) FROM task2), which should return Count=25; but it's not. So, apparently, the program isn't even going further into the cur3 which I have declared for activity=3.
I have tried using Continue Handler with cursor, too; but it didn't seem to work!
Can anyone help resolve this issue?
BEGIN
DROP TABLE IF EXISTS task2;
CREATE TABLE task2 (
ID int(11) NOT NULL AUTO_INCREMENT,
type_id int(11) DEFAULT NULL,
url varchar(100) DEFAULT NULL,
lead_id int(11) DEFAULT NULL,
createdDate datetime DEFAULT NULL,
month varchar(20) DEFAULT NULL,
year int(11) DEFAULT NULL,
month_year varchar(20) DEFAULT NULL,
PRIMARY KEY (ID)
)
BEGIN
-- INSERTING DATA FOR ACTIVITY = 1
DECLARE nurl VARCHAR(100);
DECLARE nleadid INTEGER;
DECLARE ncreateddate DATETIME;
DECLARE l_count INTEGER;
DECLARE loop_count INTEGER;
-- LOOP COUNT = 15
SET l_count = 15;
SET loop_count = 1;
read_loop:LOOP
IF loop_count > l_count THEN
LEAVE read_loop;
END IF;
IF loop_count = 1
THEN
SET nleadid = 100;
SET ncreateddate = ('2012-09-08 01:09:30');
ELSE
SET nleadid = 100 + loop_count - 1;
SET ncreateddate = (SELECT MAX(createdDate) FROM task2);
SET ncreateddate = DATE_ADD(ncreateddate, INTERVAL ELT(0.5 + RAND() * 6, '3', '5', '45', '34', '23', '68') MINUTE);
END IF;
SET nurl = ELT(0.5 + RAND() * 3, 'g.com', 'y.com', 'm.com');
INSERT INTO task2 (type_id, url, lead_id, createdDate)
VALUES ('1', nurl, nleadid, ncreateddate);
UPDATE task2
SET month = MONTHNAME(createddate), year = YEAR(createddate), month_year = CONCAT(MONTHNAME(createddate),'-', YEAR(createddate));
SET loop_count = loop_count + 1;
END LOOP read_loop;
END;
-- INSERTING THE DATA FOR ACTIVITY = 2
BEGIN
DECLARE nurl VARCHAR(100);
DECLARE nleadid INTEGER;
DECLARE ncreateddate DATETIME;
DECLARE l_count INTEGER;
DECLARE loop_count INTEGER;
-- CURSOR DECLARATION TO FETCH 10 RANDOM RECORDS FROM ACTIVITY=1
DECLARE cur2 CURSOR FOR
SELECT DISTINCT lead_id FROM task2 WHERE type_id = 1 ORDER BY RAND() LIMIT 10;
SET l_count = 10;
SET loop_count = 1;
OPEN cur2;
read_loop:LOOP
FETCH cur2 INTO nleadid;
IF loop_count > l_count THEN
SELECT loop_count_2, l_count_2;
LEAVE read_loop;
END IF;
SET nurl = ELT(0.5 + RAND() * 3, 'g.com', 'y.com', 'm.com');
SET ncreateddate = (SELECT MAX(createdDate) FROM task2 WHERE lead_id = nleadid);
SET ncreateddate = DATE_ADD(ncreateddate, INTERVAL ELT(0.5 + RAND() * 6, '3', '5', '45', '34', '23', '68') MINUTE);
INSERT INTO task2 (type_id, url, lead_id, createdDate)
VALUES ('2', nurl, nleadid, ncreateddate);
UPDATE task2
SET month = MONTHNAME(createddate), year = YEAR(createddate), month_year = CONCAT(MONTHNAME(createddate),'-', YEAR(createddate));
SET loop_count = loop_count + 1;
SELECT COUNT(*) FROM task2;
END LOOP read_loop;
SELECT COUNT(*) FROM task2;
CLOSE cur2;
END;
-- INSERTING DATA FOR ACTIVITY = 3
BEGIN
DECLARE nurl VARCHAR(100);
DECLARE nleadid INTEGER;
DECLARE ncreateddate DATETIME;
DECLARE l_count INTEGER;
DECLARE loop_count INTEGER;
-- CURSOR DECLARATION FOR SELECTING 5 RANDOM LEADS FROM ACTIVITY=2
DECLARE cur3 CURSOR FOR
SELECT DISTINCT lead_id FROM task2 WHERE type_id = 2 ORDER BY RAND() LIMIT 5;
SET l_count = 5;
SET loop_count = 1;
OPEN cur3;
read_loop:LOOP
IF loop_count > l_count THEN
LEAVE read_loop;
END IF;
FETCH cur3 INTO nleadid;
SET nurl = CONCAT(ELT(0.5 + RAND() * 3, 'g.com', 'y.com', 'm.com'), ELT(0.5 + RAND() * 3, '/home.html', '/index.html', '/about.html'));
SELECT nurl;
SET ncreateddate = (SELECT MAX(createdDate) FROM task2 WHERE lead_id = nleadid);
SET ncreateddate = DATE_ADD(ncreateddate, INTERVAL ELT(0.5 + RAND() * 6, '3', '5', '45', '34', '23', '68') MINUTE);
SELECT ncreateddate;
INSERT INTO task2 (type_id, url, lead_id, createdDate)
VALUES ('3', nurl, nleadid, ncreateddate);
UPDATE task2
SET month = MONTHNAME(createddate), year = YEAR(createddate), month_year = CONCAT(MONTHNAME(createddate),'-',YEAR(createddate));
SET loop_count =loop_count + 1;
END LOOP read_loop;
CLOSE cur3;
END;
SELECT * FROM task2;
END

SQL Error: No data - zero rows fetched, selected, or processed

CREATE PROCEDURE KC_update_pricing()
BEGIN
DECLARE u_sku VARCHAR(10) DEFAULT "";
DECLARE u_product_size VARCHAR(4) DEFAULT "";
DECLARE u_product_name VARCHAR(100) DEFAULT "";
DECLARE u_chargeble_area DECIMAL DEFAULT 0.0;
DECLARE u_user_id VARCHAR(10) DEFAULT "";
DECLARE u_last_update DATE;
DECLARE cur1 CURSOR FOR
SELECT
sku,
product_size,
product_name,
chargeble_area,
user_id,
last_update
FROM kcproduct_test_load
WHERE last_update >= (SELECT DATE_FORMAT(DATE_SUB(max(last_update), INTERVAL 1 DAY), '%d-%m-%Y')
FROM kcpricing_test_load);
OPEN Cur1;
LOOP
FETCH cur1
INTO u_sku, u_product_size, u_product_name, u_chargeble_area, u_user_id, u_last_update;
IF (u_product_size = 'S')
THEN
SET u_shipping = 99;
ELSEIF (u_product_size = 'M')
THEN
SET u_shipping = 149;
ELSEIF (u_product_size = 'L')
THEN
SET u_shipping = 199;
ELSEIF (u_product_size = 'XS')
THEN
SET u_shipping = 99;
ELSEIF (u_product_size = 'XXS')
THEN
SET u_shipping = 69;
ELSE
SET u_shipping = 199;
END IF;
UPDATE kcpricing_test_load
SET base_price = (u_chargeble_area * 150)
WHERE sku = u_SKU;
END LOOP;
END;
have an exception command in the cursor some thing like below :
Exception
When NO_DATA_FOUND then
continue
end;
it will help to avoid no data found error.

Cursor in mysql stored procedure executes only 1 iteration

I have been struck in this stored procedure for 2 days now.
Here's the code
BEGIN
DECLARE in_township_id INT DEFAULT 2;
DECLARE in_billing_month INT DEFAULT 1;
DECLARE in_billing_month_string VARCHAR(15) DEFAULT 'January';
DECLARE in_billing_year INT DEFAULT 2016;
DECLARE in_account_id INT DEFAULT 1;
DECLARE out_status INT DEFAULT 0;
DECLARE in_invoice_date DATETIME DEFAULT CURRENT_DATE();
DECLARE _no_flats INT;
DECLARE _current_month_data_exists INT;
DECLARE _flat_id INT;
DECLARE _current_billing_month, _current_billing_year INT;
DECLARE _next_billing_month, _next_billing_year INT;
DECLARE _current_balance, _new_balance FLOAT DEFAULT 0;
DECLARE _maintenance, _power_backup, _service_tax, _penalty FLOAT DEFAULT 0;
DECLARE _maintenance_price, _power_backup_price, _service_tax_price, _balance_price, _penalty_price FLOAT DEFAULT 0;
DECLARE _consumed_units INT;
DECLARE _penal_interest_remark, _maintenance_bill_remark, _power_backup_remark, _service_tax_remark, _maintenance_account_remark VARCHAR(100);
DECLARE _total_penalty, _total_maintenance, _total_power_backup, _total_service_tax FLOAT DEFAULT 0;
DECLARE _all_flats_cursor CURSOR FOR SELECT id FROM flat_resident_v WHERE township_id=2;
DECLARE CONTINUE HANDLER FOR NOT FOUND SET _no_flats=1;
DECLARE EXIT HANDLER FOR SQLEXCEPTION
BEGIN
ROLLBACK;
SET out_status=2;
SELECT 'An error has occurred, operation rollbacked and the stored procedure was terminated';
END;
START TRANSACTION;
SET _current_billing_month=in_billing_month;
SET _current_billing_year=in_billing_year;
SET _next_billing_month=in_billing_month;
SET _next_billing_year=in_billing_year;
IF in_billing_month=1 THEN
SET _current_billing_month=12;
SET _current_billing_year=in_billing_year-1;
END IF;
IF in_billing_month=12 THEN
SET _next_billing_month=1;
SET _next_billing_year=in_billing_year+1;
ELSE
SET _next_billing_month = in_billing_month+1;
END IF;
SELECT CONCAT('On account of billing month ', in_billing_month_string) INTO _maintenance_account_remark;
SELECT penalty, rate_maintenance, rate_power_backup, service_tax_rate
INTO _penalty, _maintenance, _power_backup, _service_tax FROM account_master WHERE id=in_account_id;
SELECT CONCAT('Charged # ', _penalty*1200, '%') INTO _penal_interest_remark;
SELECT CONCAT('Charged # Rs. ', _maintenance, '/sq. feet') INTO _maintenance_bill_remark;
SELECT CONCAT('Charged # Rs. ', _power_backup, '/unit') INTO _power_backup_remark;
SELECT CONCAT('Charged # ', _service_tax_price*100, '%') INTO _service_tax_remark;
SET out_status = 0;
INSERT INTO temp(value1, value2) VALUES('SUCCESS', 'Initialization Completed');
OPEN _all_flats_cursor;
SET _no_flats=0;
ALL_FLATS_LOOP: LOOP
FETCH _all_flats_cursor INTO _flat_id;
IF _no_flats=1 THEN
INSERT INTO temp(value1, value2) VALUES('LOOP BREAK', _no_flats);
LEAVE ALL_FLATS_LOOP;
END IF;
IF _no_flats=0 THEN
INSERT INTO temp(value1, value2) VALUES('INSIDE LOOP', _no_flats);
INSERT INTO temp(value1, value2) VALUES('FLAT_ID', _flat_id);
SELECT count(FLATS.id) INTO _current_month_data_exists FROM account_flat_ledger as FLATS
WHERE FLATS.flat_id=_flat_id AND FLATS.debit_month=in_billing_month
AND FLATS.debit_year=in_billing_year FOR UPDATE;
IF _current_month_data_exists=0 THEN
SET out_status = 1;
INSERT INTO temp(value1, value2) VALUES('_current_month_data_exists', 'FAILED: Data not exists for billing year');
LEAVE ALL_FLATS_LOOP;
END IF;
SELECT consumed_units INTO _consumed_units FROM account_power_backup_usage
WHERE flat_id=_flat_id AND month=in_billing_month AND year=in_billing_year;
INSERT INTO temp(value1, value2) VALUES('SUCCESS', 'Power Ok');
SELECT balance INTO _current_balance FROM account_flat_ledger as FLATS
WHERE FLATS.flat_id=_flat_id AND FLATS.debit_month=_current_billing_month AND FLATS.debit_year=_current_billing_year FOR UPDATE;
IF _current_balance>0 THEN
SET _penalty_price = _penalty*_current_balance;
END IF;
SET _maintenance_price = _maintenance*1000;
SET _power_backup_price = _power_backup*_consumed_units;
SET _service_tax_price = _service_tax * (_maintenance+_power_backup);
SET _new_balance = _current_balance + _penalty + _maintenance + _power_backup + _service_tax;
INSERT INTO temp(value1, value2) VALUES('SUCCESS', 'All Values Set');
UPDATE account_flat_ledger SET penal_interest=_penalty_price, maintenance_bill=_maintenance_price, service_tax=_service_tax_price,
power_backup=_power_backup_price, opening_balance=_current_balance,received_amount=0, balance=_new_balance,
debit_date=CURDATE(), penal_interest_remark=_penal_interest_remark, maintenance_bill_remark=_maintenance_bill_remark,
power_backup_remark=_power_backup_remark, service_tax_remark=_service_tax_remark
WHERE flat_id=_flat_id AND debit_month=in_billing_month AND debit_year=in_billing_year;
INSERT INTO account_flat_ledger(flat_id, debit_month, debit_year)
VALUES(_flat_id, _next_billing_month, _next_billing_year);
INSERT INTO temp(value1, value2) VALUES('SUCCESS', 'Insertion of new Flats OK');
SET _total_maintenance = _total_maintenance + (_maintenance_price
+ _power_backup_price + _service_tax_price + _penalty_price);
SET _total_penalty = _total_penalty + _penalty_price;
SET _total_power_backup = _total_power_backup + _power_backup_price;
SET _total_service_tax = _total_service_tax + _service_tax_price;
INSERT INTO temp(value1, value2) VALUES('SUCCESS', 'Flat over');
END IF;
END LOOP ;
CLOSE _all_flats_cursor;
IF out_status != 0 THEN
ROLLBACK;
END IF;
SELECT #out_status;
END IF;
COMMIT;
END
Previously I have done this whole thing using Java code (using ResultSets and PreparedStatements). But someone told me to use stored procedure for this purpose to make things handy and efficient.
Problem: The loop i.e. Cursor executes only ones, but there are 3 records present in the table.
I used logging into temp table to trace the error but couldn't find.

Mysql cursor fetches only first row

Mysql cursor fetches only first row and when it has fetched the second row the row_not_found variable is set to false and cursor close.
Please look into below SP:
CREATE DEFINER = 'root'#'localhost'
PROCEDURE billingv2test.SP_CreateRecurringBillingOrders(IN _billingDate DATETIME,
IN _defaultBillingFrequency INT,
IN _IsForcedExecution BIT)
BEGIN
DECLARE _userId char(36);
DECLARE _billingStartDate datetime;
DECLARE _billingEndDate datetime;
DECLARE _cmd VARCHAR(4000);
DECLARE _userBillingHistoryId char(36);
DECLARE _paymentOrderId char(36);
DECLARE _orderNumber VARCHAR(100);
DECLARE _totalChargeAmount DECIMAL(15, 6);
DECLARE _couponChargeAmount DECIMAL(15, 6);
DECLARE _pendingChargeAmount DECIMAL(15, 6);
DECLARE _isError BIT;
DECLARE _noOfUsersProcessed BIT;
DECLARE _billingResourceType VARCHAR(20);
DECLARE _RowNo INT;
DECLARE _defaultDateTime DATETIME;
DECLARE record_not_found INTEGER DEFAULT 0;
DECLARE user_list varchar(200);
DECLARE ProcessUsersForRecurringBilling_Cursor CURSOR FOR
SELECT OwnerId FROM UserBillingInfo
WHERE NextBillingDate IS NOT NULL
AND cast(NextBillingDate as date) <= cast( _billingDate as date)
AND IsProcessPending = 0
AND IsDeleted = 0
AND BillingStatus <> 'Delinquent'
ORDER BY NextBillingDate;
DECLARE CONTINUE HANDLER FOR NOT FOUND SET record_not_found = 1;
SET _isError = 0;
SET _noOfUsersProcessed = 0;
SET _defaultDateTime = '1900-01-01 00:00:00';
SET _userBillingHistoryId = UUID();
INSERT INTO BillingHistory( Id, BillingStartTime, BillingEndTime, Status, NoOfUsersProcessed, CreateTime, UpdateTime )
VALUES ( _userBillingHistoryId, UTC_TIMESTAMP(), NULL , 'Started', 0, UTC_TIMESTAMP(), UTC_TIMESTAMP());
OPEN ProcessUsersForRecurringBilling_Cursor;
allusers: LOOP
FETCH ProcessUsersForRecurringBilling_Cursor INTO _userId;
IF record_not_found THEN
LEAVE allusers;
END IF;
SET user_list = CONCAT(IFNULL(user_list,''),", ",_userId);
SET _isError = 0;
SET _orderNumber = '';
SET _totalChargeAmount = '0';
SET _couponChargeAmount = '0';
SET _pendingChargeAmount = '0';
UPDATE UserBillingInfo SET IsProcessPending = 1 WHERE OwnerId = _userId;
SET _billingStartDate = _defaultDateTime;
SELECT
IFNULL(InvoiceDate, _defaultDateTime) INTO _billingStartDate
FROM
PaymentOrder
WHERE OwnerId = _userId AND OrderStatus IN ('Success', 'Submitted')
ORDER BY CreateTime DESC
LIMIT 1;
SELECT NextBillingDate INTO _billingEndDate FROM UserBillingInfo WHERE OwnerId = _userId;
SET _orderNumber = UUID();
SET _orderNumber = SUBSTRING(_orderNumber, 0, LOCATE('-', _orderNumber));
-- CALL SP_CreateRecurringBillingPaymentOrder
CALL SP_CreateRecurringBillingPaymentOrder
(_userId, _billingStartDate, _billingEndDate, _orderNumber, _userBillingHistoryId, _paymentOrderId);
SELECT Amount INTO _totalChargeAmount FROM PaymentOrder WHERE Id = _paymentOrderId;
SET _pendingChargeAmount = _totalChargeAmount;
UPDATE PaymentOrder set ChargeAmount = _pendingChargeAmount, UpdateTime = UTC_TIMESTAMP()
WHERE Id = _paymentOrderId;
UPDATE ResourceUsageProcessed SET BillingStatus = 'Completed'
WHERE PaymentOrderId = _paymentOrderId AND BillingStatus = 'Processing';
SET _noOfUsersProcessed = _noOfUsersProcessed + 1;
END LOOP allusers;
CLOSE ProcessUsersForRecurringBilling_Cursor;
UPDATE BillingHistory SET NoOfUsersProcessed = _noOfUsersProcessed, Status = 'Completed', BillingEndTime = UTC_TIMESTAMP()
WHERE Id = _userBillingHistoryId;
END
hey this may sound silly but try this
IF record_not_found=1 THEN
LEAVE allusers;

MYSQL - function not returning expected results

I'm building a site for property rentals. I'm doing the search bit now and I'm trying to setup a function I can call for each property. The function needs to grab all rows from the rental_periods table attached to a given property then work out the best (cheapest) weekly price.
I have the following tables setup already.
properties - One line for each property
rental_periods - Multiple lines for each property, tied with id.
Each line is selfcatered or catered.
If selfcatered the price needs to be worked out from prices given in:
WeekDayPerDay - wdpd
WeekEndPerNight - wepn
Monthly price - monthly
Week price - wk
If catered the prices can be given in:
PerPersonPerNight - pppn
PerNight - pn
PerPersonPerWeek - pppw
I need a function that takes a property id and then grabs all periods that apply, then depending on selfcatered/catered works out the price per week that's best.
What I've got so far doesn't seem to be working. It either returns NULL or returns 100000.00 (my upper limit default price).
Here's the code
DELIMITER $$
CREATE FUNCTION get_price(myid INT)
RETURNS VARCHAR(20)
BEGIN
DECLARE done INT DEFAULT 0;
DECLARE price decimal(30,3) default 100000.000;
DECLARE id INT;
DECLARE prop_id INT;
DECLARE type enum('catered','selfcatered');
DECLARE name varchar(45);
DECLARE `from` date;
DECLARE `to` date;
DECLARE currency varchar(45);
DECLARE so tinyint;
DECLARE wk decimal(30,3);
DECLARE wepn decimal(30,3);
DECLARE wdpd decimal(30,3);
DECLARE monthly decimal(30,3);
DECLARE extra decimal(30,3);
DECLARE pppn decimal(30,3);
DECLARE pn decimal(30,3);
DECLARE pppw decimal(30,3);
DECLARE minstay int;
DECLARE maxstay int;
DECLARE breakfast varchar(45);
DECLARE annual TINYINT;
DECLARE cur1 CURSOR FOR SELECT * FROM rental_periods WHERE prop_id = myid;
DECLARE CONTINUE HANDLER FOR NOT FOUND SET done = 1;
OPEN cur1;
REPEAT
FETCH cur1 INTO id, prop_id, type, name, `from`, `to`, currency, so, wk, wepn, wdpd, minstay, maxstay, monthly, extra, pppn, pn, pppw, breakfast, annual;
IF NOT done THEN
IF (#type = "selfcatered") THEN
IF (#wdpd > 0 AND (#wdpd * 7) < #price) THEN
SET price = #wdpd * 7;
END IF;
IF (#wepn > 0 AND (#wepn * 7) < #price) THEN
SET price = #wepn * 7;
END IF;
IF ((#wdpd > 0 AND #wepn > 0) AND
(#wdpd * 5 + #wepn * 2) < #price) THEN
SET price = #wdpd * 5 + #wepn * 2;
END IF;
IF (#monthly > 0 AND (#monthly / (52 / 12)) < #price) THEN
SET price = #monthly / (52 / 12);
END IF;
IF (#wk > 0 AND #wk < #price) THEN
SET price = #wk;
END IF;
ELSE
IF (#pppn > 0 AND (#pppn * 7) < #price) THEN
SET price = #pppn * 7;
END IF;
IF (#pn > 0 AND (#pn * 7) < #price) THEN
SET price = #pn * 7;
END IF;
IF (#pppw > 0 AND (#pppw) < #price) THEN
SET price = #pppw;
END IF;
END IF;
END IF;
UNTIL done END REPEAT;
CLOSE cur1;
RETURN price;
END $$
i'm hoping/not thats it's something stupid with how I've arranged it, or my lack of pure MySQL.
ANY help would be very helpful.
EDIT:
Here's an example row from rental_periods:
INSERT INTO `rental_periods` (`id`, `prop_id`, `type`, `name`, `from`, `to`, `currency`, `so`, `wk`, `wepn`, `wdpd`, `minstay`, `maxstay`, `monthly`, `extra`, `pppn`, `pn`, `pppw`, `breakfast`, `annual`)
VALUES (64732, 32, 'selfcatered', 'Summer', '2012-06-01', '2012-08-31', NULL, 1, '350', '60', '100', '', '', '', '', NULL, NULL, NULL, NULL, 0);
I'd expect the function to return 350 picked from the per week column. However if the wepn was 30, not 60, I'd expect 210 to come back (worked out from 7 * wepn prices).
The code im testing in SP:
DELIMITER $$
CREATE procedure tmp_get_price(myid INT)
BEGIN
DECLARE done INT DEFAULT 0;
DECLARE price decimal(30,3) default 100000.000;
DECLARE id INT;
DECLARE prop_id INT;
DECLARE type enum('catered','selfcatered');
DECLARE name varchar(45);
DECLARE `from` date;
DECLARE `to` date;
DECLARE currency varchar(45);
DECLARE so tinyint;
DECLARE wk decimal(30,3);
DECLARE wepn decimal(30,3);
DECLARE wdpd decimal(30,3);
DECLARE monthly decimal(30,3);
DECLARE extra decimal(30,3);
DECLARE pppn decimal(30,3);
DECLARE pn decimal(30,3);
DECLARE pppw decimal(30,3);
DECLARE minstay int;
DECLARE maxstay int;
DECLARE breakfast varchar(45);
DECLARE annual TINYINT;
DECLARE cur1 CURSOR FOR SELECT id, prop_id, type, name, `from`, `to`, currency, so, wk, wepn, wdpd, minstay, maxstay, monthly, extra, pppn, pn, pppw, breakfast, annual FROM rental_periods WHERE prop_id = myid;
DECLARE CONTINUE HANDLER FOR NOT FOUND SET done = 1;
OPEN cur1;
REPEAT
FETCH cur1 INTO id, prop_id, type, name, `from`, `to`, currency, so, wk, wepn, wdpd, minstay, maxstay, monthly, extra, pppn, pn, pppw, breakfast, annual;
IF NOT done THEN
IF (type = "selfcatered") THEN
IF (wdpd > 0 AND (wdpd * 7) < price) THEN
SET price = wdpd * 7;
END IF;
IF (wepn > 0 AND (wepn * 7) < price) THEN
SET price = wepn * 7;
END IF;
IF ((wdpd > 0 AND wepn > 0) AND
(wdpd * 5 + wepn * 2) < price) THEN
SET price = wdpd * 5 + wepn * 2;
END IF;
IF (monthly > 0 AND (monthly / (52 / 12)) < price) THEN
SET price = monthly / (52 / 12);
END IF;
IF (wk > 0 AND wk < price) THEN
SET price = wk;
END IF;
ELSE
IF (pppn > 0 AND (pppn * 7) < price) THEN
SET price = pppn * 7;
END IF;
IF (pn > 0 AND (pn * 7) < price) THEN
SET price = pn * 7;
END IF;
IF (pppw > 0 AND (pppw) < price) THEN
SET price = pppw;
END IF;
END IF;
END IF;
UNTIL done END REPEAT;
CLOSE cur1;
select price;
END $$
still doesnt work... :( am i being stupid... cant see why this wont work..?!?
gets the periods...
goes throught each one...
if the price is less set it....
select price....?!?
if i put multiple selects in... for example inside the cursor.
only the very bottom one fires and returns 100000.000
i've setup all the value fields as decimals and not allowing NULL...
any thoughts when im going wrong...? also tried debug by inserting in to log table... never fires..?!
Need to read more on cursors this seams a good place to start...
http://www.kbedell.com/2009/03/02/a-simple-example-of-a-mysql-stored-procedure-that-uses-a-cursor/