How to update mysql data with event and remove the event after - mysql

I have a mysql table that looks like this
| begintime | endtime | begindate | enddate | state |
+------------+----------+------------+----------+-------+
| TIME | TIME | DATE | DATE | string|
+------------+----------+------------+----------+-------+
I have this code
CREATE EVENT Update
ON SCHEDULE
EVERY 1 SECOND
DO
UPDATE tablename SET tablename.state = CASE
WHEN (SELECT CURRENT_TIME() FROM DUAL)>=tablename.begintime AND (SELECT CURDATE()>= tablename.begindate) THEN "Available"
WHEN (SELECT CURRENT_TIME() FROM DUAL)>tablename.endtime AND (SELECT CURDATE()= tablename.enddate) THEN "Finished"
ELSE "Not Available"
END
I want the server to be always checking if any of those statements is true, and I dont know how to remove the event when:
WHEN (SELECT CURRENT_TIME() FROM DUAL)>tablename.endtime AND (SELECT CURDATE()= tablename.enddate) THEN "Finished
Thanks for your help.

please try this one.
SET GLOBAL event_scheduler = ON;
DROP EVENT IF EXISTS Update1;
CREATE EVENT Update1
ON SCHEDULE
EVERY 1 SECOND
DO
UPDATE tablename SET tablename.state =
CASE
WHEN NOW() BETWEEN CONCAT(tablename.begindate,' ',tablename.begintime) AND CONCAT(tablename.enddate,' ',tablename.endtime) THEN "Available"
WHEN NOW() > CONCAT(tablename.enddate,' ',tablename.endtime) THEN "Finished"
ELSE "Not Available"
END;
To drop the event after setting to "Finished" try using something like this
SET GLOBAL event_scheduler = ON;
DROP EVENT IF EXISTS Update1;
DELIMITER //
CREATE EVENT Update1
ON SCHEDULE
EVERY 1 SECOND
DO BEGIN
SELECT #begindate := begindate,
#begintime:= begintime,
#enddate := enddate,
#endtime := endtime FROM tablename;
IF (NOW() BETWEEN CONCAT(#begindate,' ',#begintime) AND CONCAT(#enddate,' ',#endtime)) THEN
UPDATE tablename SET state = 'Available';
ELSEIF (NOW() < CONCAT(#begindate,' ',#begintime)) THEN
UPDATE tablename SET state = 'Not Available';
ELSEIF (NOW() > CONCAT(#enddate,' ',#endtime)) THEN
UPDATE tablename SET state = 'Finished';
DROP EVENT IF EXISTS Update1;
END IF;
END//
DELIMITER ;

Related

Events dynamic value passing

My current snippet has added here.
Problem is while doing an insert into mail table that time I have Triggered Value: lc_calc_value so lc_calc_value should be inserted from select query but it's not going to insert value.
Code :
CREATE EVENT custom_alert ON SCHEDULE EVERY 600 SECOND DO
BEGIN
DECLARE lc_current_time DATETIME;
DECLARE lc_calc_value DECIMAL(8,2);
SET lc_current_time = CONVERT_TZ(NOW(), ##session.time_zone, '+0:00');
SELECT AVG(billseconds) AS calc_value FROM table1 c WHERE c.date > lc_current_time + INTERVAL -600 SECOND AND c.date <= lc_current_time AND group_id = 7 into lc_calc_value ;
IF lc_calc_value <= 10.00 THEN
INSERT INTO custom_report(triggered_value,type,status,email,group_od,threshold_value,period,triggered_date) value (lc_calc_value,2,1,'abc.com',7,10.00,600,lc_current_time);
INSERT INTO mail (`date`,`subject`,`body`,`from`,`to`,`status`,`reseller_id`) VALUES (1,lc_current_time,'Alarm : ACD','Hello Admin,
Name : ACD,
Type : Gateway,
Threshold : 10.00
Period : 100
Trunk/CLI : new_test
Triggered Value : lc_calc_value','abc#ghi.com','abc.com',1,0);
END IF;
Is there already an entry in "custom_report" with the same PK?
Also your insert looks wrong. When I read it, you try to insert:
mail.date = 1
mail.subject = lc_current_time
mail.body = "Alarm...
...
I assume you messed up the query.

generated column with condition sql

mysql command to generate a column from other column according to condition
loan_amount | installment | start_date | status
------------------------------------------------------------------
500 | 100 | 2018-1-1 |
if (loan_amount % installment != 0) then month_required to pay = loan_amount / installment + 1
else month_required = loan_amount / installment;
then i want to check by adding month_required to start_date if it has crossed current date. If not then status would generate "incomplete" else "complete" .
delimiter //
set #month = "0";
create trigger `status_check` before insert on `loan`
for each row
begin
if NEW.loan_amount% NEW.installment != 0
then set #month NEW.loan_amount/ NEW.installment +1;
else set #month = NEW.loan_amount/NEW.installment;
end if ;
if NOW() <= dateadd(NEW.start_date,INTERVAL #month MONTH)
then set NEW.status = "incomplete";
else set NEW.status = "complete";
end if;
end;
//
DELIMITER ;
what is the error here? please help.
I Can't make the real answer as you don't provide all your database field nor a data sample, but some BEFORE INSERT and BEFORE UPDATE Trigger will probably do the job.
This is the base for the BEFORE INSERT :
DELIMITER //
DROP TRIGGER IF EXISTS `trg_test_insert`;
//
CREATE TRIGGER `trg_test_insert`
BEFORE INSERT ON `table`
FOR EACH ROW
BEGIN
IF NEW.loan_amount % NEW.installment != 0 THEN
SET NEW.month_required = NEW.loan_amount / NEW.installment + 1;
ELSE
SET NEW.month_required = NEW.loan_amount / NEW.installment;
END IF;
END;
//
DELIMITER ;
Take a look at MySQL 5.7 Reference Manual / ... / Trigger Syntax and Examples
And at :
MYSQL Triggers - how to store the result of a calculated field

ZF2 MYSQL Event Manager Custom Query

I am trying to save an event in MySQL event Manager with two parts as shown below.
I can add it successfully via PHPMyAdmin, but with ZF2 TAblegateway no joy..
Any solution - directly through php would be acceptable for now..
$this->tableGateway->getAdapter()->driver->getConnection()>execute($eventSql);
$eventSql =
"DELIMITER |
CREATE EVENT slacheckevent9
ON SCHEDULE AT CURRENT_TIMESTAMP + INTERVAL 2 MINUTE
DO
BEGIN
UPDATE sla AS T1,
(SELECT eventdata FROM eventdata WHERE eventname = 'CUSTOMER
CONTACTED' AND instructionid=3) AS T2
SET T1.actualtime=T2.eventdata WHERE T1.id = 9;
UPDATE sla
SET slasuccess= CASE
WHEN actualtime <= duetime THEN true
ELSE slasuccess
END
WHERE id = 9
;
END |
DELIMITER ;";
Simply:
$eventSql = "
CREATE EVENT slacheckevent9
ON SCHEDULE AT CURRENT_TIMESTAMP + INTERVAL 2 MINUTE
DO
BEGIN
UPDATE sla AS T1,
(SELECT eventdata FROM eventdata WHERE eventname = 'CUSTOMER
CONTACTED' AND instructionid=3) AS T2
SET T1.actualtime=T2.eventdata WHERE T1.id = 9;
UPDATE sla
SET slasuccess= CASE
WHEN actualtime <= duetime THEN true
ELSE slasuccess
END
WHERE id = 9
;
END
";
$this->tableGateway->getAdapter()->query($eventSql, \Zend\Db\Adapter\Adapter::QUERY_MODE_EXECUTE);

MySQL events doesn't run eventhough every settings is enable

I have created simple event but it doesn't run:
DELIMITER |
CREATE EVENT myevent3
ON SCHEDULE EVERY 1 second
STARTS current_timestamp()
ENDS CURRENT_TIMESTAMP + INTERVAL 1 DAY
DO
BEGIN
UPDATE hiberante.animal SET name = name + 'a' where id = 6;
END |
DELIMITER ;
I have done:
SET GLOBAL event_scheduler = ON;
Also done:
SELECT * FROM INFORMATION_SCHEMA.EVENTS;
and
SELECT * FROM mysql.event;
And it still doesn't want to start working.
In my process list:
SHOW PROCESSLIST;

Event Scheduler in Mysql not running

I have written event scheduler in MySQL. After executing, this event is not working at all. The task which is written is not happening. Below is my event scheduler,
DELIMITER $$
CREATE EVENT `Untravelled_Deduction` ON SCHEDULE EVERY 1 DAY STARTS '2016-04-01 06:42:00' ON COMPLETION NOT PRESERVE ENABLE DO BEGIN
DECLARE UserId INT;
DECLARE v_finished INT DEFAULT 0;
DECLARE GetDate DATE DEFAULT DATE(NOW());
/*get each user who's account is activated and not swiped for the given date*/
DECLARE UnTravelled CURSOR FOR
SELECT DISTINCT U.user_id
FROM `um.user` U
INNER JOIN `um.user_ps.pass` UP ON UP.user_id=U.user_id
INNER JOIN `ps.pass` P ON P.pass_id=UP.pass_id AND P.status_id=4
INNER JOIN `um.user_trs.tariff` UT ON UT.user_id = U.user_id
WHERE U.is_verified_email=1 AND U.is_active=1
AND UT.user_tariff_id = (
/*check user available_journeys journeys is available or not*/
SELECT MAX(UT2.user_tariff_id) FROM `um.user_trs.tariff` UT2 WHERE UT2.user_id = UT.user_id
AND UT2.available_journeys>0 AND UT2.current_balance>0 AND UT2.end_date>=GetDate
);
DECLARE CONTINUE HANDLER FOR NOT FOUND SET v_finished=1;
/*Match th date with holiday list*/
SET #HolidayCount=(SELECT COUNT(*) FROM `holiday_list` WHERE DATE(holiday_date)=GetDate);
/*Match date for saturday and sunday*/
IF DAYOFWEEK(GetDate)!=1 AND DAYOFWEEK(GetDate)!=7 AND #HolidayCount=0 THEN
OPEN UnTravelled;
get_userid:LOOP
FETCH UnTravelled INTO UserId;
IF v_finished=1 THEN
LEAVE get_userid;
END IF;
/*Find user is registered for two way or one way, if #UserRouteCount=2 i.e. two way, #UserRouteCount=1 i.e. one way, */
SET #UserRouteCount = (SELECT COUNT(*) FROM `um.user_rm.route` WHERE user_id = UserId);
/*Get user swipe count to check how many times he swiped for the day. if only one and he is one way then deduct only once*/
SET #UserSwipeCount = (SELECT COUNT(*) FROM `ts.swipe_information` WHERE user_id = UserId AND DATE(swipe_in_time)=GetDate);
/*if user is two way and swiped only once for the day then deduct only once*/
IF (#UserRouteCount=2 AND #UserSwipeCount=1) THEN
SET #RouteCount=1;
ELSE
SET #RouteCount=#UserRouteCount;
END IF;
SET #i=1;
/*Get ticket details on this date for the user*/
SET #TicketCont= (SELECT COUNT(ticket_id) FROM `ts.ticket` WHERE DATE(`issued_on`)=GetDate AND user_id=UserId);
SET #IsInsert=0;
/*Check if any ticket is issued for the user on this date. if not he not travelled and go ahead to deduct*/
IF (#TicketCont=0) THEN
SET #IsInsert=1;
END IF;
/*check if ticket issued once, if he is two way user then decuct once*/
IF (#TicketCont=1 AND #UserRouteCount=2) THEN
SET #IsInsert=1;
END IF;
WHILE #i <= #RouteCount DO
IF (#IsInsert=1) THEN
/*Generate ticket if not exist for given date*/
/*get user current tariff plan*/
SET #UserTariffId = (SELECT user_tariff_id FROM `um.user_trs.tariff` WHERE user_id =UserId AND expired_on >= GetDate AND available_journeys > 0 ORDER BY user_tariff_id LIMIT 1);
IF(#UserTariffId IS NOT NULL)
THEN
SET #PerJourneyCost = (SELECT per_journey_cost FROM `um.user_trs.tariff` WHERE user_tariff_id=#UserTariffId );
SET #TariffCurrentBalance = (SELECT current_balance FROM `um.user_trs.tariff` WHERE user_tariff_id=#UserTariffId );
INSERT INTO `ts.ticket`(user_id,ticket_type_id,ticket_number,issued_on,
amount_charged,user_tariff_id,opening_balance,is_untravelled) VALUES
(UserId,1,'',UTC_TIMESTAMP(),#PerJourneyCost,#UserTariffId, #TariffCurrentBalance,1);
IF #PerJourneyCost IS NOT NULL THEN
/*Update user current tariff balance and number of journeys*/
UPDATE `um.user_trs.tariff` SET current_balance=(current_balance-#PerJourneyCost),
available_journeys =(available_journeys-1) WHERE user_tariff_id = #UserTariffId;
END IF;
END IF;
END IF;
SET #i=#i+1;
END WHILE;
/*Update user balance details and update Updated date in User table*/
UPDATE `um.user` SET updated_on=UTC_TIMESTAMP() WHERE user_id = UserId;
END LOOP get_userid;
CLOSE UnTravelled;
END IF;
END$$
DELIMITER ;
Couldn't rectify the issue, Please suggest any improvements.
Regards
Sangeetha
Creating event is not enough.
Make sure that scheduler is actually enabled:
MariaDB [(none)]> show global variables like 'event_scheduler';
+-----------------+-------+
| Variable_name | Value |
+-----------------+-------+
| event_scheduler | OFF |
+-----------------+-------+
1 row in set (0.00 sec)
If not, try to activate it at runtime:
SET GLOBAL event_scheduler = ON;
or
SET ##global.event_scheduler = ON;
Or in /etc/my.conf (or wherever your config is located), and restart server:
event_scheduler=ON
Official docs:
Event Scheduler Configuration
Event scheduler options