Home Database Mysql Tutorial MySQL5触发器教程

MySQL5触发器教程

Jun 07, 2016 pm 04:04 PM
Tutorial Agreement programming trigger style

约定和编程风格 每次我想要演示实际代码时,我会对mysql客户端的屏幕就出现的代码进行调整,将字体改成Courier,使他们看起来与普通文本不一样(让大家区别程序代码和正文)。在这里举个例子: mysql DROP FUNCTION f;Query OK, 0 rows affected (0.00 sec)

约定和编程风格
每次我想要演示实际代码时,我会对mysql客户端的屏幕就出现的代码进行调整,将字体改成Courier,使他们看起来与普通文本不一样(让大家区别程序代码和正文)。在这里举个例子:
mysql> DROP FUNCTION f;
Query OK, 0 rows affected (0.00 sec)
Copy after login
如果实例比较大,则需要在某些行和段落间加注释,同时我会用将"mysql> CREATE PROCEDURE p () -> BEGIN -> /* This procedure does nothing */ END;// Query OK, 0 rows affected (0.00 sec) 有时候我会将例子中的"mysql>"和"->"这些系统显示去掉,你可以直接将代码复制到mysql客户端程序中(如果你现在所读的不是电子版的,可以在mysql.com网站下载相关脚本) 所以的例子都已经在Suse 9.2 Linux、Mysql 5.0.3公共版上测试通过。在您阅读本书的时候,Mysql已经有更高的版本,同时能支持更多OS了,包括Windows,Sparc,HP-UX。因此这里的例子将能正常的运行在您的电脑上。但如果运行仍然出现故障,可以咨询你认识的资深Mysql用户,这样就能得到比较好的支持和帮助。
为什么要用触发器
我们在MySQL 5.0中包含对触发器的支持是由于以下原因:
MySQL早期版本的用户长期有需要触发器的要求。
我们曾经许诺支持所有ANSI标准的特性。
您可以使用它来检查或预防坏的数据进入数据库。
您可以改变或者取消INSERT, UPDATE以及DELETE语句。
您可以在一个会话中监视数据改变的动作。
Copy after login
在这里我假定大家都读过"MySQL新特性"丛书的第一集--"MySQL存储过程",那么大家都应该知道MySQL至此存储过程和函数,那是很重要的知识,因为在触发器中你可以使用在函数中使用的语句。特别举个例子:
复合语句(BEGIN / END)是合法的.
流控制(Flow-of-control)语句(IF, CASE, WHILE, LOOP, WHILE, REPEAT, LEAVE,ITERATE)也是合法的.
变量声明(DECLARE)以及指派(SET)是合法的.
允许条件声明.
异常处理声明也是允许的.
但是在这里要记住函数有受限条件:不能在函数中访问表.

因此在函数中使用以下语句是非法的。
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

在触发器中也有完全一样的限制.
Copy after login
触发器相对而言比较新,因此会有(bugs)缺陷.所以我在这里给大家警告,就像我在存储过程书中所说那样.不要在含有重要数据的数据库中使用这个触发器,如果需要的话在一些以测试为目的的数据库上使用,同时在你对表创建触发器时确认这些数据库是默认的。
语法
1. 语法:命名规则

CREATE TRIGGER  
FOR EACH ROW

Copy after login
触发器必须有名字,最多64个字符,可能后面会附有分隔符.它和MySQL中其他对象的命名方式基本相象.
这里我有个习惯:就是用表的名字+'_'+触发器类型的缩写.因此如果是表t26,触发器是在事件UPDATE(参考下面的点(2)和(3))之前(BEFORE)的,那么它的名字就是t26_bu。
2. 语法:触发时间

CREATE TRIGGER 
{ BEFORE | AFTER } 
FOR EACH ROW


触发器有执行的时间设置:可以设置为事件发生前或后。

3. 语法:事件

CREATE TRIGGER 
{ BEFORE | AFTER }
{ INSERT | UPDATE | DELETE } 
FOR EACH ROW


同样也能设定触发的事件:它们可以在执行insert、update或delete的过程中触发。
4. 语法:表

CREATE TRIGGER 
{ BEFORE | AFTER }
{ INSERT | UPDATE | DELETE }
ON  

触发器是属于某一个表的:当在这个表上执行插入、
更新或删除操作的时候就导致触发器的激活.
我们不能给同一张表的同一个事件安排两个触发器。

5. 语法:( 步长)触发间隔

CREATE TRIGGER 
{ BEFORE | AFTER }
{ INSERT | UPDATE | DELETE }
ON 
FOR EACH ROW 

触发器的执行间隔:FOR EACH ROW子句通知触发器
每隔一行执行一次动作,而不是对整个表执行一次。

6. 语法:语句

CREATE TRIGGER 
{ BEFORE | AFTER }
{ INSERT | UPDATE | DELETE }
ON 
FOR EACH ROW
  TO ;
也可以通过这样收回权限:
REVOKE CREATE TRIGGER ON  FROM ;
Copy after login
关于旧的和新创建的列的标识
在触发器的SQL语句中,你可以关联表中的任意列。但你不能仅使用列的名称去标识,那会使系统混淆,因为那里可能会有列的新名(这可能正是你要修改的,你的动作可能正是要修改列名),还有列的旧名存在。因此你必须用这样的语法来标识: "NEW . column_name"或者"OLD . column_name".这样在技术上处理(NEW | OLD . column_name)新和旧的列名属于创建了过渡变量("transition variables")。
对于INSERT语句,只有NEW是合法的;对于DELETE语句,只有OLD才合法;而UPDATE语句可以在和NEW以及OLD同时使用。下面是一个UPDATE中同时使用NEW和OLD的例子。
CREATE TRIGGER t21_au
BEFORE UPDATE ON t22
FOR EACH ROW
BEGIN
SET @old = OLD . s1;
SET @new = NEW.s1;
END;//

现在如果t21表中的s1列的值是55,那么执行了
"UPDATE t21 SET s1 = s1 + 1"之后@old的值会变成55,
而@new的值将会变成56。
Copy after login
Example of CREATE and INSERT CREATE和INSERT的例子
创建有触发器的表
这里所有的例程中我都假定大家的分隔符已经设置成//(DELIMITER //)。
CREATE TABLE t22 (s1 INTEGER)//
CREATE TRIGGER t22_bi
BEFORE INSERT ON t22
FOR EACH ROW
BEGIN
SET @x = 'Trigger was activated!';
SET NEW.s1 = 55;
END;//
Copy after login
在最开始我创建了一个名字为t22的表,然后在表t22上创建了一个触发器t22_bi,当我们要向表中的行插入时,触发器就会被激活,执行将s1列的值改为55的动作。
使用触发器执行插入动作
mysql> INSERT INTO t22 VALUES (1)//
让我们看如果向表t2中插入一行数据触发器对应的表会怎么样? 这里的插入的动作是很常见的,我们不需要触发器的权限来执行它。甚至不需要知道是否有触发器关联。
mysql> SELECT @x, t22.* FROM t22//
+------------------------+------+
| @x | s1 |
+------------------------+------+
| Trigger was activated! | 55 |
+------------------------+------+
1 row in set (0.00 sec)
Copy after login
大家可以看到INSERT动作之后的结果,和我们预期的一样,x标记被改动了,同时这里插入的数据不是我们开始输入的插入数据,而是触发器自己的数据。
"check"完整性约束例子
什么是"check"约束
在标准的SQL语言中,我们可以在(CREATE TABLE)创建表的过程中使用"CHECK (condition)",
例如:
CREATE TABLE t25
(s1 INT, s2 CHAR(5), PRIMARY KEY (s1),
CHECK (LEFT(s2,1)='A'))
ENGINE=INNODB;
Copy after login
这里CHECK的意思是"当s2列的最左边的字符不是'A'时,insert和update语句都会非法",MySQL的视图不支持CHECK,我个人是很希望它能支持的。但如果你很需要在表中使用这样的功能,我建议大家使用触发器来实现。
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;//
Copy after login
我只需要使用BEFORE INSERT和BEFORE UPDATE语句就行了,删除了触发器不会对表有影响,同时AFTER的触发器也不能修改NEW的过程变量(transition variables)。为了激活触发器,我执行了向表中的行插入s1=0的数据,之后只要执行符合LEFT(s2,1) 'A'条件的动作都会失败:
INSERT INTO t25 VALUES (0,'a') /* priming the pump */ //
INSERT INTO t25 VALUES (5,'b') /* gets error '23000' */ //
Don't Believe The Old MySQL Manual
Copy after login
该抛弃旧的MySQL的手册了
我在这里警告大家不要相信过去的MySQL手册中所说的了。我们已经去掉了关于触发器的错误的语句,但是仍旧有很多旧版本的手册在网上,举个例子,这是一个德国的Url上的: http://dev.mysql.com/doc/mysql/de/ANSI_diff_Triggers.html.  这个手册上说触发器就是存储过程,忘掉吧,你也已经看见了,触发器就是触发器,而存储过程还是存储过程。 手册上还说触发器可以从其他表上来删除,或者是当你删除一个事务的时候激发,无论他说的是什么意思,忘掉吧,MySQL不会去实现这些的。 最后关于说使用触发器会对查询速度产生影响的说法也是错的,触发器不会对查询产生任何影响。
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
4 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Best Graphic Settings
4 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. How to Fix Audio if You Can't Hear Anyone
4 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
WWE 2K25: How To Unlock Everything In MyRise
1 months ago By 尊渡假赌尊渡假赌尊渡假赌

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

In summer, you must try shooting a rainbow In summer, you must try shooting a rainbow Jul 21, 2024 pm 05:16 PM

After rain in summer, you can often see a beautiful and magical special weather scene - rainbow. This is also a rare scene that can be encountered in photography, and it is very photogenic. There are several conditions for a rainbow to appear: first, there are enough water droplets in the air, and second, the sun shines at a low angle. Therefore, it is easiest to see a rainbow in the afternoon after the rain has cleared up. However, the formation of a rainbow is greatly affected by weather, light and other conditions, so it generally only lasts for a short period of time, and the best viewing and shooting time is even shorter. So when you encounter a rainbow, how can you properly record it and photograph it with quality? 1. Look for rainbows. In addition to the conditions mentioned above, rainbows usually appear in the direction of sunlight, that is, if the sun shines from west to east, rainbows are more likely to appear in the east.

How to retrieve the wrong chain of virtual currency? Tutorial on retrieving the wrong chain of virtual currency transfer How to retrieve the wrong chain of virtual currency? Tutorial on retrieving the wrong chain of virtual currency transfer Jul 16, 2024 pm 09:02 PM

The expansion of the virtual market is inseparable from the circulation of virtual currency, and naturally it is also inseparable from the issue of virtual currency transfers. A common transfer error is the address copy error, and another error is the chain selection error. The transfer of virtual currency to the wrong chain is still a thorny problem, but due to the inexperience of transfer operations, novices often transfer the wrong chain. So how to recover the wrong chain of virtual currency? The wrong link can be retrieved through a third-party platform, but it may not be successful. Next, the editor will tell you in detail to help you better take care of your virtual assets. How to retrieve the wrong chain of virtual currency? The process of retrieving virtual currency transferred to the wrong chain may be complicated and challenging, but by confirming the transfer details, contacting the exchange or wallet provider, importing the private key to a compatible wallet, and using the cross-chain bridge tool

Why do you need to know histograms to learn photography? Why do you need to know histograms to learn photography? Jul 20, 2024 pm 09:20 PM

In daily shooting, many people encounter this situation: the photos on the camera seem to be exposed normally, but after exporting the photos, they find that their true form is far from the camera's rendering, and there is obviously an exposure problem. Affected by environmental light, screen brightness and other factors, this situation is relatively normal, but it also brings us a revelation: when looking at photos and analyzing photos, you must learn to read histograms. So, what is a histogram? Simply understood, a histogram is a display form of the brightness distribution of photo pixels: horizontally, the histogram can be roughly divided into three parts, the left side is the shadow area, the middle is the midtone area, and the right side is the highlight area; On the left is the dead black area in the shadows, while on the far right is the spilled area in the highlights. The vertical axis represents the specific distribution of pixels

What are the recommended documentation and tutorials for the Java framework? What are the recommended documentation and tutorials for the Java framework? Jun 02, 2024 pm 09:30 PM

Having the right documentation and tutorials at your fingertips is crucial to using Java frameworks effectively. Recommended resources include: SpringFramework: Official Documentation and Tutorials SpringBoot: Official Guide Hibernate: Official Documentation, Tutorials and Practical Cases ServletAPI: Official Documentation, Tutorials and Practical Cases JUnit: Official Documentation and Tutorials Mockito: Official Documentation and Tutorials

Collection of C++ programming puzzles: stimulate thinking and improve programming skills Collection of C++ programming puzzles: stimulate thinking and improve programming skills Jun 01, 2024 pm 10:26 PM

C++ programming puzzles cover algorithm and data structure concepts such as Fibonacci sequence, factorial, Hamming distance, maximum and minimum values ​​of arrays, etc. By solving these puzzles, you can consolidate C++ knowledge and improve algorithm understanding and programming skills.

Problem-Solving with Python: Unlock Powerful Solutions as a Beginner Coder Problem-Solving with Python: Unlock Powerful Solutions as a Beginner Coder Oct 11, 2024 pm 08:58 PM

Pythonempowersbeginnersinproblem-solving.Itsuser-friendlysyntax,extensivelibrary,andfeaturessuchasvariables,conditionalstatements,andloopsenableefficientcodedevelopment.Frommanagingdatatocontrollingprogramflowandperformingrepetitivetasks,Pythonprovid

The Key to Coding: Unlocking the Power of Python for Beginners The Key to Coding: Unlocking the Power of Python for Beginners Oct 11, 2024 pm 12:17 PM

Python is an ideal programming introduction language for beginners through its ease of learning and powerful features. Its basics include: Variables: used to store data (numbers, strings, lists, etc.). Data type: Defines the type of data in the variable (integer, floating point, etc.). Operators: used for mathematical operations and comparisons. Control flow: Control the flow of code execution (conditional statements, loops).

Demystifying C: A Clear and Simple Path for New Programmers Demystifying C: A Clear and Simple Path for New Programmers Oct 11, 2024 pm 10:47 PM

C is an ideal choice for beginners to learn system programming. It contains the following components: header files, functions and main functions. A simple C program that can print "HelloWorld" needs a header file containing the standard input/output function declaration and uses the printf function in the main function to print. C programs can be compiled and run by using the GCC compiler. After you master the basics, you can move on to topics such as data types, functions, arrays, and file handling to become a proficient C programmer.

See all articles