Schl f Infrmatin and Cmputer Technlgy Sirindhrn Internatinal Institute f Technlgy Thammasat University ITS351 Database Prgramming Labratry Labratry #13: Trigger Objective: - T learn build in trigger in MySQL - T learn hw t write trigger t MySQL - T learn hw call trigger in MySQL t PHP MySQL Resurce: http://www.mysql.cm/ 1 Create Trigger in MYSQL A SQL trigger is a set f SQL statements stred in the database catalg. A SQL trigger is executed r fired whenever an event assciated with a table ccurs e.g., insert, update r delete. A SQL trigger is a special type f stred prcedure. It is special because it is nt called directly like a stred prcedure. The main difference between a trigger and a stred prcedure is that a trigger is called autmatically when a data mdificatin event is made against a table whereas a stred prcedure must be called explicitly. It is imprtant t understand SQL trigger s advantages and disadvantages s that yu can use it apprpriately. In the fllwing sectins, we will discuss abut the advantages and disadvantages f using SQL triggers. Advantages f using SQL triggers SQL triggers prvide an alternative way t check the integrity f data. SQL triggers can catch errrs in business lgic in the database layer. SQL triggers prvide an alternative way t run scheduled tasks. By using SQL triggers, yu dn t have t wait t run the scheduled tasks because the triggers are invked autmatically befre r after a change is made t the data in the tables. SQL triggers are very useful t audit the changes f data in tables. @Cpyright ICT Prgram, Sirindhrn Internatinal Institute f Technlgy, Thammasat University 1/7
Disadvantages f using SQL triggers SQL triggers nly can prvide an extended validatin and they cannt replace all the validatins. Sme simple validatins have t be dne in the applicatin layer. Fr example, yu can validate user s inputs in the client side by using JavaScript r in the server side using server side scripting languages such as JSP, PHP, ASP.NET, Perl, etc. SQL triggers are invked and executed invisibly frm client-applicatins therefre it is difficult t figure ut what happen in the database layer. SQL triggers may increase the verhead f the database server. In MySQL, a trigger is a set f SQL statements that is invked autmatically when a change is made t the data n the assciated table. A trigger can be defined t be invked either befre r after the data is changed by INSERT, UPDATE r DELETE statement. BEFORE INSERT activated befre data is inserted int the table. AFTER INSERT activated after data is inserted int the table. BEFORE UPDATE activated befre data in the table is updated. AFTER UPDATE activated after data in the table is updated. BEFORE DELETE activated befre data is remved frm the table. AFTER DELETE activated after data is remved frm the table. MySQL trigger limitatins MySQL triggers cver all features defined in the standard SQL. Hwever, there are sme limitatins that yu shuld knw befre using them in yur applicatins. MySQL triggers cannt: Use SHOW, LOAD DATA, LOAD TABLE, BACKUP DATABASE, RESTORE, FLUSH and RETURN statements. Use statements that cmmit r rllback implicitly r explicitly such as COMMIT, ROLLBACK, START TRANSACTION, LOCK/UNLOCK TABLES, ALTER, CREATE, DROP, RENAME, etc. Use prepared statements such as PREPARE, EXECUTE, etc. Use dynamic SQL statements. @Cpyright ICT Prgram, Sirindhrn Internatinal Institute f Technlgy, Thammasat University 2/7
CREATE TRIGGER Syntax CREATE [DEFINER = { user CURRENT_USER }] TRIGGER trigger_name trigger_time trigger_event ON tbl_name FOR EACH ROW [trigger_rder] trigger_bdy trigger_time: { BEFORE AFTER } trigger_event: { INSERT UPDATE DELETE } trigger_rder: { FOLLOWS PRECEDES } ther_trigger_name This statement creates a new trigger. A trigger is a named database bject that is assciated with a table, and that activates when a particular event ccurs fr the table. The trigger becmes assciated with the table named tbl_name, which must refer t a permanent table. Yu cannt assciate a trigger with a TEMPORARY table r a view. MySQL takes the DEFINER user int accunt when checking trigger privileges as fllws: At CREATE TRIGGER time, the user wh issues the statement must have the TRIGGER privilege. At trigger activatin time, privileges are checked against the DEFINER user. This user must have these privileges: The TRIGGER privilege fr the subject table. The SELECT privilege fr the subject table if references t table clumns ccur using OLD.cl_name r NEW.cl_name in the trigger bdy. The UPDATE privilege fr the subject table if table clumns are targets f SET NEW.cl_name = value assignments in the trigger bdy. Whatever ther privileges nrmally are required fr the statements executed by the trigger. Here is a simple example that assciates a trigger with a table, t activate fr INSERT peratins. The trigger acts as an accumulatr, summing the values inserted int ne f the clumns f the table. mysql> CREATE TABLE accunt (acct_num INT, amunt DECIMAL(10,2)); Query OK, 0 rws affected (0.03 sec) mysql> CREATE TRIGGER ins_sum BEFORE INSERT ON accunt -> FOR EACH ROW SET @sum = @sum + NEW.amunt; Query OK, 0 rws affected (0.06 sec) @Cpyright ICT Prgram, Sirindhrn Internatinal Institute f Technlgy, Thammasat University 3/7
The CREATE TRIGGER statement creates a trigger named ins_sum that is assciated with the accunt table. It als includes clauses that specify the trigger actin time, the triggering event, and what t d when the trigger activates: The keywrd BEFORE indicates the trigger actin time. In this case, the trigger activates befre each rw inserted int the table. The ther permitted keywrd here is AFTER. The keywrd INSERT indicates the trigger event; that is, the type f peratin that activates the trigger. In the example, INSERT peratins cause trigger activatin. Yu can als create triggers fr DELETE and UPDATE peratins. The statement fllwing FOR EACH ROW defines the trigger bdy; that is, the statement t execute each time the trigger activates, which ccurs nce fr each rw affected by the triggering event. In the example, the trigger bdy is a simple SET that accumulates int a user variable the values inserted int the amunt clumn. The statement refers t the clumn as NEW.amunt which means the value f the amunt clumn t be inserted int the new rw. T use the trigger, set the accumulatr variable t zer, execute an INSERT statement, and then see what value the variable has afterward: mysql> SET @sum = 0; mysql> INSERT INTO accunt VALUES(137,14.98),(141,1937.50),(97,-100.00); mysql> SELECT @sum AS 'Ttal amunt inserted'; +----------------------------+ Ttal amunt inserted +----------------------------+ 1852.48 +----------------------------+ In this case, the value f @sum after the INSERT statement has executed is 14.98 + 1937.50-100, r 1852.48. T destry the trigger, use a DROP TRIGGER statement. Yu must specify the schema name if the trigger is nt in the default schema: mysql> DROP TRIGGER test.ins_sum; If yu drp a table, any triggers fr the table are als drpped. @Cpyright ICT Prgram, Sirindhrn Internatinal Institute f Technlgy, Thammasat University 4/7
Trigger names exist in the schema namespace, meaning that all triggers must have unique names within a schema. Triggers in different schemas can have the same name. In additin t the requirement that trigger names be unique fr a schema, there are ther limitatins n the types f triggers yu can create. In particular, there cannt be multiple triggers fr a given table that have the same trigger event and actin time. Fr example, yu cannt have tw BEFORE UPDATE triggers fr a table. T wrk arund this, yu can define a trigger that executes multiple statements by using the BEGIN... END cmpund statement cnstruct after FOR EACH ROW. (An example appears later in this sectin.) Within the trigger bdy, the OLD and NEW keywrds enable yu t access clumns in the rws affected by a trigger. OLD and NEW are MySQL extensins t triggers; they are nt case sensitive. In an INSERT trigger, nly NEW.cl_name can be used; there is n ld rw. In a DELETE trigger, nly OLD.cl_name can be used; there is n new rw. In an UPDATE trigger, yu can use OLD.cl_name t refer t the clumns f a rw befre it is updated and NEW.cl_name t refer t the clumns f the rw after it is updated. A clumn named with OLD is read nly. Yu can refer t it (if yu have the SELECT privilege), but nt mdify it. Yu can refer t a clumn named with NEW if yu have the SELECT privilege fr it. In a BEFORE trigger, yu can als change its value with SET NEW.cl_name = value if yu have the UPDATE privilege fr it. This means yu can use a trigger t mdify the values t be inserted int a new rw r used t update a rw. (Such a SET statement has n effect in an AFTER trigger because the rw change will have already ccurred.) In a BEFORE trigger, the NEW value fr an AUTO_INCREMENT clumn is 0, nt the sequence number that is generated autmatically when the new rw actually is inserted. By using the BEGIN... END cnstruct, yu can define a trigger that executes multiple statements. Within the BEGIN blck, yu als can use ther syntax that is permitted within stred rutines such as cnditinals and lps. Hwever, just as fr stred rutines, if yu use the mysql prgram t define a trigger that executes multiple statements, it is necessary t redefine the mysql statement delimiter s that yu can use the ; statement delimiter within the trigger definitin. The fllwing example illustrates these pints. It defines an UPDATE trigger that checks the new value t be used fr updating each rw, and mdifies the value t be within the range frm 0 t 100. This must be a BEFORE trigger because the value must be checked befre it is used t update the rw: @Cpyright ICT Prgram, Sirindhrn Internatinal Institute f Technlgy, Thammasat University 5/7
mysql> delimiter // mysql> CREATE TRIGGER upd_check BEFORE UPDATE ON accunt -> FOR EACH ROW -> BEGIN -> IF NEW.amunt < 0 THEN -> SET NEW.amunt = 0; -> ELSEIF NEW.amunt > 100 THEN -> SET NEW.amunt = 100; -> END IF; -> END;// mysql> delimiter ; It can be easier t define a stred prcedure separately and then invke it frm the trigger using a simple CALL statement. This is als advantageus if yu want t execute the same cde frm within several triggers. There are limitatins n what can appear in statements that a trigger executes when activated: The trigger cannt use the CALL statement t invke stred prcedures that return data t the client r that use dynamic SQL. (Stred prcedures are permitted t return data t the trigger thrugh OUT r INOUT parameters.) The trigger cannt use statements that explicitly r implicitly begin r end a transactin, such as START TRANSACTION, COMMIT, r ROLLBACK. (ROLLBACK t SAVEPOINT is permitted because it des nt end a transactin.). Prir t MySQL 5.0.10, triggers cannt cntain direct references t tables by name. @Cpyright ICT Prgram, Sirindhrn Internatinal Institute f Technlgy, Thammasat University 6/7
Wrksheet 1. Imprt database named BANK frm given resurce file in database flder. The fllwing figure shws the structure f BANK database. Nte that all fields must set t allw NULL value except primary key. accunt Table Field Type Length Values Extra Primary Key id INT Aut_increment Yes n VARCHAR 20 name VARCHAR 200 creditlimit DOUBLE bal Flat transactin Table Field Type Length Values Extra Primary Key id INT Aut_increment Yes type char 1 amunt flat date datetime accid INT 2. Write Trigger t prevent transactin edit. 3. Write Trigger t check balance f mney befre insert. If balance f mney is nt enugh t Withdraw, please alert message Nt enugh mney, hwever, if balance f mney is enugh, insert the recrd and update new balance t bal clumn. Exercise Extend wrksheet and write trigger cde t stre delete transactin t lg table. The fllwing table shws structure f transactin_histry transactin_histry Table Field Type Length Values Extra Primary Key id INT Aut_increment Yes type char 1 amunt flat date datetime accid INT deldate datetime * Deldate clumn will stre current date/time when user deletes transactin. @Cpyright ICT Prgram, Sirindhrn Internatinal Institute f Technlgy, Thammasat University 7/7