MySQL 5.0-triggers

Source: Internet
Author: User
Tags mysql manual
Conventions and styles conventions and programming styles

Every time I want to demonstrate the actualCodeI will adjust the code displayed on the screen of the mysql client and change the font to courier to make them look different from normal text (to make everyone differentProgramCode and body ). Here is an example:

Mysql> drop function F;
Query OK, 0 rows affected (0.00 Sec)

If the instance is large, you need to add comments between some rows and paragraphs, and I will place the "<--" symbol on the right side of the page to emphasize. For example:

Mysql> Create procedure P ()
-> Begin
->/* This procedure does nothing */<--
-> End ;//
Query OK, 0 rows affected (0.00 Sec)

Sometimes I will remove the "mysql>" and "->" systems in the example. You can copy the Code directly to the mysql client program (if you are not reading an electronic version, you can download related scripts on the mysql.com website)

Therefore, all the examples have passed the test on SuSE 9.2 Linux and MySQL 5.0.3 public edition. When you read this book, MySQL has a higher version and supports more operating systems, including windows, Linux, and HP-UX. So the example here will run normally on your computer. However, if the operation still fails, you can consult a senior MySQL user you know so that you can get better support and help.

Why does why triggers Use Triggers?

The reason why we support triggers in MySQL 5.0 is as follows:

Users of earlier MySQL versions have long-term requirements for triggers.
We have promised to support all ANSI-standard features.
You can use it to check or prevent bad data from entering the database.
You can change or cancel insert, update, and delete statements.
You can monitor data changes in a session.

Here, I assume that everyone has read "MySQL new feature" series's first episode-"MySQL Stored Procedures", so everyone should know that MySQL stored procedures and functions are very important, because you can use the statements used in functions in triggers. For example:

The compound statement (begin/end) is valid.

The flow-of-control statement (if, case, while, loop, while, repeat, leave, iterate) is also valid.

Variable Declaration (declare) and assignment (SET) are legal.

Allow condition declaration.

Exception Handling statement is also allowed.

However, remember that a function has a restriction: you cannot access a table in the function. Therefore, the following statement is invalid in the function.

Alter 'cache Index' call commit create Delete

Drop 'flush privileges' grant insert kill

Lock optimize repair replace revoke

Rollback savepoint 'select from table'

'Set system variable' 'set transaction'

Show 'start transaction' truncate update

The trigger also has the same restrictions.

The trigger is relatively new, so there will be (bugs) defects. so I am here to give you a warning, as I said in the stored procedure book. do not use this trigger in databases that contain important data. If necessary, use the trigger in some test-oriented databases and confirm that these databases are default when you create a trigger on a table.

Syntax

1. Syntax: Name Syntax: naming rules

Create trigger <trigger Name> <--
{Before | after}
{Insert | update | Delete}
On <Table Name>
For each row
<Trigger SQL statement>

The trigger must have a name and a maximum of 64 characters. It may be followed by a separator. It is similar to the naming method of other objects in MySQL.

Here I have a habit: using the table name + '_' + the abbreviation of the trigger type. therefore, for table t26, the trigger is before the event update (see the following points (2) and (3) (Before), then its name is t26_bu.

2. Syntax: Time Syntax: trigger time

Create trigger <trigger Name>
{Before | after} <--
{Insert | update | Delete}
On <Table Name>
For each row
<SQL statement triggered>

Trigger execution time settings: You can set the time before or after an event occurs.

3. Syntax: Event

Create trigger <trigger Name>
{Before | after}
{Insert | update | Delete} <--
On <Table Name>
For each row
<SQL statement triggered>

The trigger events can also be set: they can be triggered during the execution of insert, update, or delete.

4. Syntax: Table

Create trigger <trigger Name>
{Before | after}
{Insert | update | Delete}
On <Table Name> <--
For each row
<SQL statement triggered>

A trigger belongs to a table. When an insert, update, or delete operation is performed on the table, the trigger is activated.
We cannot schedule two triggers for the same event of the same table.

5. Syntax: granularity syntax :( step) trigger Interval

Create trigger <trigger Name>
{Before | after}
{Insert | update | Delete}
On <Table Name>
For each row <--
<SQL statement triggered>

Trigger execution interval: The for each row clause notifies the trigger to execute an action on every row instead of the entire table.

6. Syntax: Statement

Create trigger <trigger Name>
{Before | after}
{Insert | update | Delete}
On <Table Name>
For each row
<SQL statement triggered> <--

The trigger contains the SQL statement to be triggered: The statement here can be any legal statement, including compound statements, but the statements here are subject to the same restrictions as the functions.

Privileges permission

You must have considerable permissions to create a trigger ). If you are a root user, it is enough. This is different from the SQL standard. I also hope to change it to the standard as soon as possible.

Therefore, in the next MySQL version, you may see a new permission called create trigger. Then, use the following method to grant:

Grant create trigger on <Table Name> to <user or user list>;

You can also revoke permissions as follows:

Revoke create trigger on <Table Name> from <user or user list>;

Referring to old and new columns about the old and newly created column identifiers

In the SQL statement of the trigger, you can associate any column in the table. However, you cannot only use the column name to identify it, which will confuse the system, because there may be a new column name (this may be exactly what you want to modify, your action may be to modify the column name), and the old name of the Column exists. Therefore, you must use this syntax to identify:

"New. column_name" or "old. column_name". Technically, the new (New | old. column_name) and old column names belong to the created transition variable ("transition variables ").

For insert statements, only new statements are valid; For Delete statements, only old statements are valid; and update statements can be used together with new and old statements. The following is an example of using both new and old in update.

Create trigger t20000au
Before update on T22
For each row
Begin
Set @ old = old. S1;
Set @ new = new. S1;
End ;//

If the value of column S1 in Table T21 is 55, the value of @ old is 55 after "Update T21 set S1 = S1 + 1" is executed, the value of @ new will change to 56.

Example of create and insert

Create Table with trigger create table with trigger

In all the examples, I assume that the delimiter has been set to // (delimiter //).

Create Table T22 (S1 integer )//

Create trigger t22_bi
Before insert on T22
For each row
Begin
Set @ x = 'triggers was activated! ';
Set new. S1 = 55;
End ;//

At the beginning, I created a table named T22, and then created a trigger t22_bi on table T22. When we want to insert rows into the table, the trigger will be activated, change the value of column S1 to 55.

Insert on table w ith a trigger

Mysql> insert into T22 values (1 )//

Let's see what happens if we insert a data trigger row to table T2?

The insert action here is very common. We do not need the trigger permission to execute it. You do not even need to know whether a trigger is associated.

Mysql> select @ X, T22. * From T22 //
+ ------------------------ + ------ +
| @ X | S1 |
+ ------------------------ + ------ +
| Trigger was activated! | 55 |
+ ------------------------ + ------ +
1 row in SET (0.00 Sec)

We can see the results after the insert action. As we expected, the X mark is changed. At the same time, the inserted data is not the data we started to insert, but the data of the trigger.

Example of a "check" Constraint
"Check" integrity constraints

What's a "check" constraint what is a "check" Constraint

In the standard SQL language, we can use "check (condition )",
For example:

Create Table t25
(S1 int, S2 char (5), primary key (S1 ),
Check (left (S2, 1) = 'A '))
Engine = InnoDB;

Check indicates that "when the leftmost character of column S2 is not 'a', the insert and update statements are invalid." MySQL views do not support check, I personally hope it can be supported. However, if you need to use such a function in a table, we recommend that you use a trigger.

Create Table t25
(S1 int, S2 char (5 ),
Primary Key (S1 ))
Engine = InnoDB //

Create trigger t25_bi
Before insert on t25
For each row
If left (New. S2, 1) <> 'A' then set new. S1 = 0; end if ;//

Create trigger t25_bu
Before update on t25
For each row
If left (New. S2, 1) <> 'A' then set new. S1 = 0; end if ;//

I only need to use the before insert and before update statements. Deleting a trigger does not affect the table, and the after trigger cannot modify the new procedure variable (transition variables ). To activate the trigger, I inserted data S1 = 0 to the rows in the table. After that, all operations that meet the left (S2, 1) <> 'A' condition will fail:

Insert into t25 values (0, 'A')/* priming the pump *///
Insert into t25 values (5, 'B')/* gets error '000000 '*///

Don't believe the old MySQL Manual
It's time to discard the old MySQL manual.

I am here to warn you not to trust what was mentioned in the MySQL manual in the past. We have removed the statement about the trigger error, but there are still many old manuals on the Internet. For example, this is a German URL:

Http://dev.mysql.com/doc/mysql/de/ANSI_diff_Triggers.html.

In this manual, a trigger is a stored procedure. Forget it. You can see that a trigger is a trigger, and a stored procedure is a stored procedure.

The Manual also says that triggers can be deleted from other tables, or triggered when you delete a transaction. No matter what he means, forget it. MySQL will not implement this.

Finally, it is wrong to say that using a trigger will affect the query speed, and the trigger will not affect the query.

Bugs
(If something is bad, it will not be translated)
On December 14 2004, I did an "Advanced Search" in http://bugs.mysql.com for 'trigger' or
'Trigger', I found that there were 17 active bugs as of that date. Of course they might disappear
Before you read this, but just in case they havent, I'll mention the important ones. If they're still
There, you'll have to work around und them when you're trying triggers.

Bug #5859 drop table does not drop triggers.
(The trigger is not automatically deleted when the table is deleted)
When you drop a table, dropping the table's triggers shoshould be automatic IC.

Bug #5892 triggers have the wrong namespace.
(The trigger namespace is incorrect. You must add the table name before deleting the trigger. The following is an example)
You have to say "Drop trigger <Table Name>. <trigger Name> ".
The correct way is "Drop trigger <trigger Name> ".

Bug #5894 triggers with altered tables cause failed upt databases.
(Changes to the trigger table may cause damage to the database data)
Do not alter a table that has a trigger on it, until you know this is fixed.

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.