The two triggers to ensure valid data. : Before Trigger « Trigger « SQL / MySQL

Home
SQL / MySQL
1.Aggregate Functions
2.Backup Load
3.Command MySQL
4.Cursor
5.Data Type
6.Database
7.Date Time
8.Engine
9.Event
10.Flow Control
11.FullText Search
12.Function
13.Geometric
14.I18N
15.Insert Delete Update
16.Join
17.Key
18.Math
19.Procedure Function
20.Regular Expression
21.Select Clause
22.String
23.Table Index
24.Transaction
25.Trigger
26.User Permission
27.View
28.Where Clause
29.XML
SQL / MySQL » Trigger » Before Trigger 
The two triggers to ensure valid data.
       

mysql>
mysql> CREATE TABLE test (id SERIAL, percent DOUBLE);
Query OK, rows affected (0.00 sec)

mysql>
mysql> DELIMITER $$
mysql>
mysql> CREATE TRIGGER test_before_insert
    ->    BEFORE INSERT ON test FOR EACH ROW
    ->    BEGIN
    ->       IF NEW.percent < 0.0 OR NEW.percent > 1.0 THEN
    ->           SET NEW.percent = NULL;
    ->       END IF;
    -> END$$
Query OK, rows affected (0.01 sec)

mysql>
mysql> CREATE TRIGGER test_before_update
    -> BEFORE UPDATE ON test FOR EACH ROW
    -> BEGIN
    ->    IF NEW.percent < 0.0 OR NEW.percent > 1.0 THEN
    ->       SET NEW.percent = NULL;
    ->    END IF;
    -> END$$
Query OK, rows affected (0.01 sec)

mysql>
mysql> DELIMITER ;
mysql>
mysql>
mysql> INSERT INTO test (percentVALUES (-1)(0.3)(1.5);
Query OK, rows affected (0.00 sec)
Records: 3  Duplicates: 0  Warnings: 0

mysql>
mysql> SELECT FROM test;
+----+---------+
| id | percent |
+----+---------+
|  |    NULL |
|  |     0.3 |
|  |    NULL |
+----+---------+
rows in set (0.00 sec)

mysql>
mysql> UPDATE test SET percent = 1.7 WHERE id =2;
Query OK, row affected (0.00 sec)
Rows matched: 1  Changed: 1  Warnings: 0

mysql>
mysql> SELECT FROM test;
+----+---------+
| id | percent |
+----+---------+
|  |    NULL |
|  |    NULL |
|  |    NULL |
+----+---------+
rows in set (0.00 sec)

mysql>
mysql>
mysql> drop table test;
Query OK, rows affected (0.00 sec)

mysql>

   
    
    
    
    
    
    
  
Related examples in the same category
1.Before insert trigger
2.Create a 'Before update trigger'
3.Update table in a before update trigger
4.Change the NEW value based on the input in a BEFORE INSERT trigger
5.Change the NEW value based on the input in the BEFORE UPDATE trigger
6.Check inserted value with a trigger
java2s.com  | Contact Us | Privacy Policy
Copyright 2009 - 12 Demo Source and Support. All rights reserved.
All other trademarks are property of their respective owners.