MYSQL - function not returning expected results - mysql

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/

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

MySQL Find how many days it needed to get the highest positive progression

Data set:
CREATE TABLE TEMPERATURES (
CREATED DATE,
ACTUAL_TEMPERATURE FLOAT
);
INSERT INTO TEMPERATURES VALUES
('20170101',12.2),
('20170103',10.1),
('20170112',14.2),
('20170115',12.5),
('20170205',20.8),
('20170122',16.7),
('20170123',7.8),
('20170130',12.5),
('20170201',13.7),
('20170302',14.8),
('20170313',11.1),
('20170414',12.0),
('20170525',10.4);
and SQL FIDDLE of same: http://sqlfiddle.com/#!9/9b11e
I just want to find how many days it needed to get the highest positive progression ?
The result I would like to have is :
20170103 10.1
20170205 20.8
Be careful, I don't want to have :
20170123 7.8
20170302 14.8
I tried many requests and many ways and no succeed.
Is it possible and if yes, how ?
Thanks for your help.
Based on your description of the problem, I think you want:
select grp, min(created), max(created),
min(actual_temperature), max(actual_temperature)
from (select t.*,
(#grp := #grp + coalesce(prev_at > actual_temperature, 0)) as grp
from (select t.*,
(select t2.actual_temperature
from temperatures t2
where t2.created < t.created
order by t2.created desc
limit 1
) as prev_at
from temperatures t
order by created
) t cross join
(select #grp := 0) params
) t
group by grp
order by max(actual_temperature) - min(actual_temperature) desc
limit 1;
This identifies streaks of increasing temperatures. It then returns the streak with the highest difference between the maximum and minimum.
This is how I interpret your question, although your results do not fully conform to this interpretation.
Maybe you can use a function, something like this (you still need to adjust the edge cases):
DELIMITER $$
CREATE FUNCTION find_progressive(startingDate DATE)
RETURNS VARCHAR(100) DETERMINISTIC
BEGIN
DECLARE risultato int default 0;
/* current cursor*/
DECLARE curr_data DATE;
DECLARE curr_temp FLOAT;
/*current best*/
DECLARE max_temp FLOAT;
DECLARE min_temp FLOAT;
DECLARE max_created DATE;
DECLARE min_created DATE;
/* absolute best*/
DECLARE best_max_created DATE;
DECLARE best_min_created DATE;
DECLARE best_max_temp FLOAT;
DECLARE best_min_temp FLOAT;
DECLARE temptemp FLOAT;
DECLARE tempcreated DATE;
DECLARE done INTEGER DEFAULT 0;
DECLARE cursore_temperature CURSOR FOR
SELECT
created,
ACTUAL_TEMPERATURE
FROM temperatures
WHERE created > startingDate
ORDER BY created;
DECLARE CONTINUE HANDLER
FOR NOT FOUND SET done = 1;
SELECT
created,
ACTUAL_TEMPERATURE
INTO
min_created,
min_temp
FROM temperatures
ORDER BY created
LIMIT 1;
SELECT
created,
ACTUAL_TEMPERATURE
INTO
max_created,
max_temp
FROM temperatures
WHERE created > min_created
ORDER BY created
LIMIT 1;
IF min_temp > max_temp
THEN
set temptemp = min_temp;
set tempcreated =max_created;
set min_temp = max_temp;
set min_created = max_created;
set max_temp = temptemp;
set max_created = tempcreated;
END IF;
set best_max_temp = max_temp;
set best_min_temp = min_temp;
set best_max_created = max_created;
set best_min_created = min_created;
OPEN cursore_temperature;
read_loop: LOOP
FETCH cursore_temperature
INTO curr_data, curr_temp;
IF done = 1
THEN
LEAVE read_loop;
END IF;
IF curr_temp < min_temp
THEN
IF (max_temp - min_temp) > ( best_max_temp - best_min_temp)
THEN
set best_max_temp = max_temp;
set best_max_created = max_created;
set best_min_temp = min_temp;
set best_min_created = min_created;
END IF;
set min_temp = curr_temp;
set min_created = curr_data;
set max_temp = curr_temp;
set max_created = curr_data;
END IF;
IF curr_temp > max_temp
THEN
set max_temp = curr_temp;
set max_created = curr_data;
END IF;
END LOOP;
CLOSE cursore_temperature;
RETURN CONCAT_WS(' | ', best_min_created, best_min_temp, best_max_created, best_max_temp);
END$$
DELIMITER ;
and you call it like
select find_progressive('2017-01-03');
and the result is 2017-01-03 | 10.1 | 2017-02-05 | 20.8
anyway I guess it is not the best talking about optimization.

Stock Backtesting

I'm fairly new to MYSQL but I have experience programming in VBA. I'm trying to create a stored procedure which will backtest a strategy against a table of historical stock price data.The procedure will calculate the 20 Day moving average of closing stock price then if the selected day CLOSE has a price that his higher than the moving average a "buy" is initiated. If a trade is currently on, no new "buys" can be placed and if the selected day CLOSE is below the 20 day moving average a "sell" is initiated. Every time a buy or sell is placed the data is recorded in a table created called backtest results. The data I'm using is from http://finance.yahoo.com/q/hp?s=AAPL+Historical+Prices and I placed it into a table. As you can see the the data is in descending order so in order for me to back test I have to start at the earliest date which happens to be at the bottom. The problem I'm having is that no data is being inputted into this newly created table (Buy Date, Buy Price, Sell Date, Sell Price) . Can anyone spot why this is? Also is mysql suited for row-by-row processing? Thanks!
`Begin
DECLARE total_count int;
DECLARE moving_average decimal;
DECLARE move_up int;
DECLARE current_price decimal;
DECLARE count_var int;
DECLARE buy_price decimal;
DECLARE sell_price decimal;
DECLARE trade_on tinyint;
DECLARE account_balance decimal;
DECLARE start_row int;
DECLARE trade_date date;
SET #trade_on = 0;
SELECT #trade_on;
DROP TABLE IF EXISTS backtestresults;
CREATE TABLE backtestresults (buydate date,buyprice decimal, selldate date, sellprice decimal, accountbalance decimal);
SELECT COUNT(*) INTO #total_count FROM AAPL_Prices;
SELECT * FROM AAPL_Prices WHERE Special_ID = #total_count;
SET #start_row = #total_count -19;
SET #account_balance = 100000;
Loop1: WHILE (start_row > 1) DO
SELECT FORMAT(AVG(SClose),2) FROM AAPL_Prices WHERE Special_ID < #start_row + 19 AND Special_ID > #start_row INTO #moving_average;
SELECT SClose FROM AAPL_Prices WHERE Special_ID = #start_row -19 INTO #current_price;
SELECT TradeDate FROM AAPL_Prices WHERE special_ID = #start_row -19 INTO #trade_date;
IF #trade_on = 0 THEN
IF #current_price > #moving_average THEN
SET #buy_price = #current_price;
SET #trade_on = 1;
SET #account_balance = #account_balance - #buy_price;
INSERT INTO backtestresults (buyprice) values (#buy_price);
INSERT INTO backtestresults (buydate) values (#trade_date);
INSERT INTO backtestresults (balance) values (#account_balance);
End If;
END IF;
IF trade_on = 1 THEN
IF #current_price < #moving_average THEN
SET #sell_price = #current_price;
SET #trade_on = 0;
SET #account_balance = #account_balance + #buy_price;
INSERT INTO backtestresults(sellprice) values (#sell_price);
INSERT INTO backtestresults(selldate) values (#trade_date);
INSERT INTO backtestresults(balance) values (#account_balance);
END IF;
END IF;
SET #start_row = #start_row - 1;
END WHILE Loop1;
SELECT #account_balance;
DESCRIBE backtestresults;
SELECT #start_row;
End`

Case not working for my stored procedure

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;
...

Trigger not working:

I created trigger on table PENDING. Pending table has 3 columns - uniqueId , duration and maxDuration. I have another table COUNT with 2 columns - req_id, total
Here is my trigger--
CREATE TRIGGER plus3second BEFORE INSERT
ON PENDING
FOR EACH ROW
BEGIN
DECLARE req_id varchar(25);
DECLARE total int(11);
DECLARE duration int(2);
SET req_id = SUBSTR(new.uniqueId, 1, 14);
Select total into total from COUNT where req_id = 'req_id';
IF total > 100 THEN
SET duration = new.duration + 3;
IF duration < new.maxDuration Then
SET new.duration = duration;
END IF;
END IF;
END
Trigger created successfully. I fired these queries on COUNT and PENDING-
insert into COUNT values ('77711422099653',200);
insert into PENDING (uniqueId, duration, maxDuration) values ('77711422099653919893277163', 3, 20);
But trigger not working ...Where is the problem ?
Check with this trigger definition(with less conflicting names):
CREATE TRIGGER plus3second
BEFORE INSERT
ON PENDING
FOR EACH ROW
BEGIN
DECLARE tReqID varchar(25);
DECLARE tTotal int(11);
DECLARE tDuration int(2);
SET tReqID = SUBSTR(new.uniqueId, 1, 14);
SELECT total
INTO tTotal
FROM COUNT
WHERE req_id = tReqID;
IF tTotal > 100
THEN
SET tDuration = new.duration + 3;
IF tDuration < new.maxDuration
THEN
SET new.duration = tDuration;
END IF;
END IF;
END