Insert and update system time using trigger - mysql

I am using a trigger for auto increment "slno", "Cust_Id". Now i need to create a insert trigger for inserting system date for the field Created_Date and Submitted_Date. And need a update trigger for only Submitted_date (Need to update the current system time on update).
Now i am using this trigger.
DELIMITER $$
CREATE TRIGGER tg_customer_details_insert
BEFORE INSERT ON customer_details
FOR EACH ROW
BEGIN
INSERT INTO customer_details_seq VALUES (NULL);
SET NEW.Created_Date = NOW();
SET NEW.Submitted_Date = NOW();
SET NEW.Slno = coalesce((select max(Slno) from customer_details), 0) + 1;
SET NEW.Cust_id = CONCAT('CUST', LPAD(LAST_INSERT_ID(), 3, '0'));
END$$
DELIMITER ;
This works fine for insert and i don't know how to put the update trigger for the "submitted date" inside this trigger.
Thanks
Acube.

Related

how to declare variable phpmyadmin mysql triggers properly?

I have a database where whenever residential address update in user table I want it to store in history table of user. For that I'm trying to write triggers but failing miserably in phpmyadmin. Also it's not giving me proper reason why so I can correct it. This is what I have done so far.
DROP TRIGGER IF EXISTS `record_history`;
CREATE TRIGGER `record_history` AFTER UPDATE ON `s_user`
FOR EACH ROW
BEGIN
DECLARE date_current datetime;
DECLARE residential_address varchar(1000);
SET #date_current = NOW();
SET #residential_address = NEW.residential_address;
IF (#residential_address <> OLD.residential_address AND #residential_address != "" AND #residential_address IS NOT NULL) THEN
INSERT INTO history_residential_address (`s_u_id`, `residential_address`, `status`, `date_added`, `date_updated`) VALUES
(OLD.s_u_id, #residential_address, 1, #date_current, #date_current);
END IF;
END;
delimiter ;
A cleaner version of your code
DROP TRIGGER IF EXISTS `record_history`;
delimiter $$
CREATE TRIGGER `record_history` AFTER UPDATE ON `s_user`
FOR EACH ROW
BEGIN
IF (new.residential_address <> OLD.residential_address AND new.residential_address <> "" AND new.residential_address IS NOT NULL) THEN
INSERT INTO history_residential_address (`s_u_id`, `residential_address`, `status`, `date_added`, `date_updated`) VALUES
(OLD.s_u_id, new.residential_address, 1, now(), now());
END IF;
END $$
delimiter ;
If you are still having problems please add sample data from s_user as text to the question.

Trigger compare two datetime mysql

I want a trigger which compare two datetime.
Here my trigger:
EDIT :
create trigger updateRealisee after update on ladi.DSMSreservation for each row
begin
declare mnt datetime;
mnt=(select NOW());
if :new.date < mnt then
:new.realisee = 1;
end if;
end;
The error is that there are several restrictions on an after udpate trigger:
You can not create an AFTER trigger on a view.
You can not update the NEW values.
You can not update the OLD values.
However, you can change it to a before insert trigger.
I have tested the code below and it works. Of course, it only works on those you are newly inserting, not ones that already exist. For the ones that already exit.... simply run:
update TEST.DSMSreservation set realisee = 1 where date < NOW();
Then... the following complete code to create a table, trigger, and add rows provides an example how it works on newly added rows:
create database TEST;
USE TEST;
CREATE TABLE TEST.DSMSreservation
(
date DATETIME NULL DEFAULT NULL,
realisee INT NULL DEFAULT NULL
);
delimiter $$
create trigger updateRealisee before insert on TEST.DSMSreservation
for each row
begin
IF (new.date < NOW()) THEN
SET new.realisee = 1;
end if;
end;
$$
delimiter ;
INSERT INTO DSMSreservation VALUES ('2012-06-08 12:13:14',0);
INSERT INTO DSMSreservation VALUES ('2017-06-08 12:13:14',0);
INSERT INTO DSMSreservation VALUES ('2016-06-08 10:13:14',0);
INSERT INTO DSMSreservation (date) VALUES ('2016-06-08 16:13:14');
Running these two mysql statements will resolve what you were trying to accomplish with your original trigger.
Please mark as answer if this has answered your question.

mySQL trigger not firing

I have a table with 4 columns [year, v_num, t_num, percentage], I'm trying to populate percentage with v_num/t_num*100. The data is already in the table but the percentage column is NULL. I created an AFTER INSERT trigger to populate the column but it's not working. Does anyone have any suggestions?
TRIGGER
DELIMITER |
CREATE DEFINER = 'XXX' TRIGGER percentAfterUp
AFTER INSERT
ON `table`
FOR EACH ROW
BEGIN
UPDATE `table` SET percentage = v_num/t_num*100;
END|
DELIMITER ;
If you want to set a value in a row, do it with a before insert trigger, not an after insert trigger:
DELIMITER |
CREATE DEFINER = 'XXX' TRIGGER percentAfterUp
BEFORE INSERT ON `table` FOR EACH ROW
BEGIN
SET new.percentage = (new.v_num / new.t_num) * 100;
END|
DELIMITER ;
If you actually want to update all the rows, don't use a trigger, just an update statement:
UPDATE `table`
SET percentage = (v_num/t_num)*100;

I have error "#1363 - There is no NEW row in on DELETE trigger "

I have table "book" and "store_order" have relation
I want to make trigger(but it contain error):
DELIMITER $$
CREATE TRIGGER t1
before delete ON store_order
FOR EACH ROW
BEGIN
update book set number = number + NEW.quantity where ISBN = NEW.ISBN;
END
$$
DELIMITER ;
DELIMITER $$
CREATE
TRIGGER t2 AFTER delete
ON library.store_order
FOR EACH ROW BEGIN
update library.book
set library.book.number = (library.book.number + OLD.quantity)
where library.book.ISBN = OLD.ISBN;
END$$
DELIMITER ;
Use OLD instead of NEW when you want to get the deleted object.
for an example of my case. I'm getting the id of the newly added role by calling
NEW.id
and getting the same field's value while deleting by calling
OLD.id
Example:
DELIMITER $$
CREATE TRIGGER after_insert_role
AFTER INSERT ON role FOR EACH ROW
BEGIN
INSERT INTO `sync_mapping`
(`operation_type`, `table_name`, `oid`, `end_point`)
VALUES
('insert', 'role', NEW.id, 'new/role');
END $$
DELIMITER $$
CREATE TRIGGER after_delete_role
AFTER DELETE ON role FOR EACH ROW
BEGIN
INSERT INTO `sync_mapping` (`operation_type`, `table_name`, `oid`, `end_point`) VALUES
('delete', 'role', OLD.id, 'delete/role');
END $$
Whenever we are deleting the data
USE
OLD. instead of NEW.
CREATE TRIGGER user_history_delete AFTER DELETE ON user FOR EACH ROW
INSERT INTO user_history(action , name )
VALUES ("Delete" , OLD.name );

Avoid firing trigger by another trigger in MYSQL

my problem is as follows:
Table A contains list of "Tasks"
Table B contains "TaskProgress" - just an information about time spent on task, user ID, task ID and note
On table A (Tasks), I have trigger, which updates datetime of last change - column DateChanged (intended to capture datetime of edits made by user)
On table B (TaskProgress) I have trigger, which updates total time spent on a task (sum all times for given Task_ID and update column TotalTime in table A)
I wish to update DateChanged in Table A only when user mades the update (which is every time except when trigger on table B updates TotalTime)
So I wonder, whether there is a way how to tell the database not to fire TRIGGER when updating the values in another trigger.
/* set date of last change and date od closing of task */
DELIMITER $$
CREATE TRIGGER before_tasks_update
BEFORE UPDATE ON tasks
FOR EACH ROW BEGIN
SET new.DateChanged = NOW();
IF new.Status_ID = 3 THEN
SET new.DateClosed = NOW();
END IF;
END$$
DELIMITER ;
/* set total time spent on task */
DELIMITER $$
CREATE TRIGGER after_taskprogress_insert
AFTER INSERT ON taskprogress
FOR EACH ROW BEGIN
DECLARE sumtime TIME;
SET #sumtime := (SELECT SEC_TO_TIME( SUM( TIME_TO_SEC( `timeSpent` ) ) )
FROM taskprogress WHERE Task_ID = new.Task_ID);
UPDATE `tasks` SET TimeReal = #sumtime WHERE ID = new.Task_ID;
END $$
DELIMITER ;
I use MySQL 5.5.40
Thanks, zbynek
Add a check to verify that the update implies a new TimeReal value,since only the second trigger updates that column.
DELIMITER $$
CREATE TRIGGER before_tasks_update
BEFORE UPDATE ON tasks
FOR EACH ROW BEGIN
IF new.TimeReal=old.TimeReal THEN SET new.DateChanged = NOW();
END IF;
IF new.TimeReal=old.TimeReal AND new.Status_ID = 3 THEN
SET new.DateClosed = NOW();
END IF;
END$$
DELIMITER ;