Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

MySQL trigger before Insert value Checking

Tags:

mysql

triggers

I have a table staff with office column. Currently the office column do not accept NULL values. The application persisting onto this table has a bug which meant that, when the staff has not been assigned an office, it tries inserting a NULL value onto the table.

I have been asked to used a trigger to intercept the insert onto the Staff table and check if the office value is NULL and replace it with value N/A.

Below is my attempt so far, but do have error in attempt to implement. Any Ideas on how to resolve this.

CREATE TRIGGER staffOfficeNullReplacerTrigger BEFORE INSERT ON Staff
  FOR EACH ROW BEGIN
    IF (NEW.office IS NULL)
     INSERT INTO Staff SET office="N/A";
    END IF
  END;

The error:

MySQL Database Error: You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'INSERT INTO Staff SET office="N/A"; END'

like image 368
Bitmap Avatar asked Oct 11 '12 09:10

Bitmap


People also ask

How do I create a trigger before insert in SQL?

Introduction to MySQL BEFORE INSERT triggers First, specify the name of the trigger that you want to create in the CREATE TRIGGER clause. Second, use BEFORE INSERT clause to specify the time to invoke the trigger. Third, specify the name of the table that the trigger is associated with after the ON keyword.

Can MySQL trigger be used for input data validation?

Moreover, triggers are ideal for validation because they can be executed before data is inserted or updated. Triggers can also can also prevent a database transaction from being applied while providing an error message.

How do I know if MySQL trigger is working?

select * from INFORMATION_SCHEMA. TRIGGERS where EVENT_OBJECT_TABLE='client'; With this, you can filter on things like EVENT_OBJECT_TABLE (table name), TRIGGER_SCHEMA , EVENT_MANIPULATION (insert, update, delete, etc), and a slew of other attributes.


1 Answers

First, alter the table to allow NULLs:

ALTER TABLE Staff MODIFY office CHAR(40) DEFAULT "N/A";

(Change CHAR(40) to whatever is appropriate.) Then you could use as your trigger:

CREATE TRIGGER staffOfficeNullReplacerTrigger 
BEFORE INSERT 
ON Staff
  FOR EACH ROW BEGIN
    IF (NEW.office IS NULL) THEN
      SET NEW.office = "N/A";
    END IF
like image 136
unutbu Avatar answered Oct 17 '22 02:10

unutbu