"after update" trigger fires after insert in mySQL - mysql

I have 2 triggers on my table as defined...
DELIMITER $$
CRATE TRIGGER newRecordToHistory AFTER INSERT ON myTable FOR EACH ROW
BEGIN
IF (new.recordType = 1) THEN
INSERT INTO myTableHistory
(
myTableId,
someInformation,
reason,
mytimestamp,
status
)
VALUES
(
new.myTableId,
new.someInformation,
new.reason,
now(),
'NEW'
);
END IF;
END$$
DELIMITER ;
and
DELIMITER $$
CRATE TRIGGER updateRecordToHistory AFTER UPDATE ON myTable FOR EACH ROW
BEGIN
IF (new.recordType = 1) THEN
INSERT INTO myTableHistory
(
myTableId,
someinformation,
reason,
mytimestamp,
status
)
VALUES
(
new.myTableId,
new.someInformation,
new.reason,
now(),
'UPDATED'
);
END IF;
END$$
DELIMITER ;
When I insert a new record into myTable, I get 2 records in myHistoryTable...
ID someInformation reason mytimestamp status
1 'This is new' 'Needed new record' 09/12/14 08:00:00 'NEW'
1 'This is new' 'Needed new record' 09/12/14 08:00:00 'UPDATED'
I also get a record in the table when I delete. But my code handles inserting into the history table when I delete (so the user can specify the reason for deleting it) from myTable.
I would only expect only one record in myHistoryTable on insert and no extra records in the myHistoryTtable when I delete (other than the ones I put there manually). Why does this happen? And how can I avoid this?
Thanks!

Related

Increment a number field via a trigger INSERT in MySQL

I'm building a data versioning system, and I need to increment a version number each time a new row is added to the version table, but it increments once and then stops:
DELIMITER |
CREATE TRIGGER trigger2 AFTER UPDATE ON something
FOR EACH ROW
BEGIN
IF NEW.updated_at <> OLD.updated_at THEN
INSERT INTO versions_something (
`id`,
`some_id`,
`version`,
`title`,
`description`,
`created_at`,
`updated_at`
) VALUES (
null,
NEW.id,
1,
NEW.title,
NEW.description,
NOW(),
NOW()
);
END IF;
UPDATE
versions_something
SET
version = (SELECT MAX(version)) + 1
WHERE versions_something.id = LAST_INSERT_ID();
END;
|
DELIMITER ;
I've tried putting the UPDATE into a separate trigger (AFTER INSERT ON versions_something ...), but MySQL complains that it's clashing with the trigger before it.
I've tried the UPDATE on its own, using the last ID in the table and it works each time, so I have no idea what's happening.

MySQL - Insert Into 2 Tables on 1 Procedure

I need to create a procedure for inserting records into 2 tables, but on the second table, I want to insert the last ID that was inserted on the first table. Could anyone help me with this?
This is my query
DELIMITER //
DROP PROCEDURE IF EXISTS ROOM_FEATURE_INSERT;
CREATE PROCEDURE ROOM_FEATURE_INSERT (propID INT, featID INT, featNme VARCHAR(50))
BEGIN
-- BEGIN CHECK
IF NOT EXISTS
(
SELECT rFeatureName FROM COMPANY_T3s71.PROPERTY_RFEATURE PRFE
INNER JOIN COMPANY_T3s71.ROOM_FEATURE RFEA ON PRFE.rFeatureID=RFEA.rFeatureID
WHERE BINARY rFeatureName = featNme AND propertyID = propID
)
AND
(
SELECT rFeatureName FROM COMPANY_T3s71.ROOM_VIEW
WHERE BINARY rFeatureName = featNme
)
THEN
-- IF NOT EXISTS INSERT INTO 1st TABLE
INSERT INTO COMPANY_T3s71.ROOM_FEATURE (rFeatureName) VALUES (featNme);
END IF;
-- END CHECK
-- BEGIN CHECK 2nd TABLE
IF NOT EXISTS
(
SELECT propertyID, rFeatureID FROM COMPANY_T3s71.PROPERTY_RFEATURE
WHERE rFeatureID = featID AND propertyID = propID
)
THEN
-- IF NOT EXISTS INSERT INTO 2nd TABLE
INSERT INTO COMPANY_T3s71.PROPERTY_RFEATURE (propertyID, rFeatureID) VALUES (propID, featID);
END IF;
-- END CHECK 2nd TABLE
END
DELIMITER ;
How do we pass the featID param, when we just inserted it on the first INSERT query?
Thank you before hand.
Use SET featID = LAST_INSERT_ID(); after the first query and then use the variable
INSERT INTO COMPANY_T3s71.ROOM_FEATURE (rFeatureName) VALUES (featNme);
SET featID = LAST_INSERT_ID();
However, if the data is not insert at anytime then you have to make query in the if block to set the value for featID.

Get column name and values for MySQL trigger

I'm beginner with MySQL and I'm trying to create a log trigger that fills a log table like this:
DELIMITER $$
CREATE TRIGGER ai_user AFTER UPDATE ON user
FOR EACH ROW
BEGIN
INSERT INTO user_log (action,id,timestamp,column_name,old_value, new_value)
VALUES('update',NEW.id,NOW(),COLUMN.NAME,OLD.column_value, NEW.column_value);
END$$
DELIMITER ;
But I'm with problems to get the changed column name and it's old and new value.
Any help would be appreciated. Thanks.
You have to do this the painful way, one at a time:
if not (old.col1 = new.col1 or old.col1 is null and new.col1 is null)
INSERT INTO user_log(action, id, timestamp, column_name, old_value, new_value)
VALUES('update', NEW.id, NOW(), 'col1', OLD.col1, NEW.col1);
end if;
if not (old.col2 = new.col2 or old.col2 is null and new.col2 is null)
INSERT INTO user_log(action, id, timestamp, column_name, old_value, new_value)
VALUES('update', NEW.id, NOW(), 'col2', OLD.col2, NEW.col2);
end if;
. . .
Note that these do not have else clauses. You want to check for every value.
By the way, when you do updates this way, you need to be careful about types if the columns you are comparing have different types.

mysql trigger error with 2 conditions

I want to add an after insert trigger which will do the following.
The first IF condition works normally, but when it comes to the second everything stops.
Any ideas?
USE `Syslog`;
DELIMITER $$
CREATE TRIGGER `SystemEventsR_AINS` AFTER INSERT ON SystemEventsR FOR EACH ROW
IF
(exists
(select syslogtag from SystemEventsRcounter where syslogtag=
new.syslogtag)
AND
(select simpledate from SystemEventsRcounter
where syslogtag=new.syslogtag)=new.simpledate)
THEN
UPDATE SystemEventsRcounter
SET records=records+1
WHERE SystemEventsRcounter.syslogtag=new.syslogtag;
ELSE INSERT SystemEventsRcounter (simpledate, syslogtag, records) values (new.simpledate,new.syslogtag,1);
END IF
UPDATED:
What you need is INSERT INTO ... ON DUPLICATE KEY.
CREATE TRIGGER `SystemEventsR_AINS`
AFTER INSERT ON SystemEventsR
FOR EACH ROW
INSERT INTO SystemEventsRcounter (simpledate, syslogtag, records)
VALUES (NEW.simpledate, NEW.syslogtag, 1)
ON DUPLICATE KEY UPDATE records = records + 1;
In order for it to work you need to create a unique composite index on (simpledate, syslogtag)
CREATE UNIQUE INDEX idx_u_simpledate_syslogtag
ON SystemEventsRcounter (simpledate, syslogtag);
Here is SQLFiddle demo.
If you wanted it your way then it might look like
DELIMITER $$
CREATE TRIGGER `SystemEventsR_AINS`
AFTER INSERT ON SystemEventsR
FOR EACH ROW
BEGIN
IF (
SELECT COUNT(*) simpledate
FROM SystemEventsRcounter
WHERE syslogtag = NEW.syslogtag
AND simpledate = NEW.simpledate
) > 0 THEN
UPDATE SystemEventsRcounter
SET records = records + 1
WHERE SystemEventsRcounter.syslogtag = NEW.syslogtag;
ELSE
INSERT INTO SystemEventsRcounter (simpledate, syslogtag, records)
VALUES (NEW.simpledate, NEW.syslogtag, 1);
END IF;
END$$
DELIMITER ;
Here is SQLFiddle demo.

How do I get multiple MySQL statements in one scheduled event?

I am trying to do two statements in one scheduled event but it is not working. It wont do anything. Could you please help me figure out what is wrong?
delimiter |
CREATE EVENT resetTimeClockTimeToday
ON SCHEDULE EVERY 1 DAY STARTS '2012-07-10 00:00:00' DO
BEGIN
UPDATE timeclock.employees SET timeToday = 0;
UPDATE timeclock.punches SET missedOut = 1 WHERE timeOUT IS NULL;
END|
delimiter ;
You need to correctly use a different delimiter, e.g.:
DROP EVENT IF EXISTS `Daily Event`;
DELIMITER $$
CREATE DEFINER=`root`#`localhost` EVENT `Daily event` ON SCHEDULE EVERY 1 DAY STARTS '2015-03-06 00:30:00' ON COMPLETION PRESERVE ENABLE DO
BEGIN
-- Newly due summary sheets
UPDATE `summaries`
SET `status` = 'DUE'
WHERE `status` = 'OPEN'
AND NOW() >= LAST_DAY(CONCAT(`year`, '-', `month`, '-01'));
-- Alert user that didn't clock out
INSERT INTO `alerts` (`from`, `to`, `subject`, `message`)
SELECT ....;
-- Alert manager that didn't clock out
INSERT INTO `alerts` (`from`, `to`, `subject`, `message`)
SELECT ....;
-- Alert for stale tickets
INSERT INTO `alerts` (`from`, `to`, `subject`, `message`)
SELECT ....;
END;
$$;
I restarted the MySQL service and it worked!