Here is a sample MYSQL Trigger that demonstrates how to changes or intercept the values been passed to the database table and change or manipulate using IF statements.
I have create only with very simple IF statement and only for a numeric, date, and text field. There is no limit to what you can do with a trigger. This trigger also demonstrates that you can have multiple conditions in a single trigger.
This MySQL SQL script was created for a quick reference and to help someone with very little knowledge of SQL trigger to give a basic understanding of MySQL triggers.
Sample MySQL Trigger:
CREATE TRIGGER dwdata.t_iCopyDocIDsAndChangeStatus
BEFORE INSERT ON dwdata.sampleen
FOR EACH ROW
/* Move the value from one column to another */
SET NEW.DOCID = NEW.DWDOCID;
/* Check a text field with IF statement */
IF NEW.DOCTYPE = 'Offer'
SET NEW.STATUS = 'Collect Money';
/* Check the numeric field with IF Statement */
IF NEW.AMOUNT >= 1000
SET NEW.STATUS = 'Big Dollars';
/* Check if the date is equal to today's date */
IF DATE_FORMAT(NEW.DATE, '%m/%d/%Y') = DATE_FORMAT(CURDATE(), '%m/%d/%Y')
SET NEW.STATUS = 'Collect money today';
To drop or delete a MySQL Trigger you will run the following command (example this trigger):
DROP TRIGGER dwdata.t_iCopyDocIDsAndChangeStatus
2 thoughts on “MySQL INSERT Trigger with IF Condition Statements”
CREATE TRIGGER dwdata2.tr_uRemoveDollarFirstCharacter
BEFORE UPDATE ON dwdata2.xp_docs
FOR EACH ROW
/** Update the data been inserted **/
IF SUBSTRING(NEW.SPARE1, 1, 1) = ‘$’ THEN
SET NEW.SPARE1 = SUBSTRING(NEW.SPARE1, 2, LENGTH(NEW.SPARE1));
Oh, it’s nice code.. 🙂 Thanks!
Comments are closed.