search
HomeDatabaseMysql Tutorialsql 触发器trigger 创建与用法

sql trigger 创建与用法

发器也是一种带名的pl/sql块。触发器类似于过程和函数,因为它们都是拥有声明

、执行和异常处理过程的带名pl/sql块。与包类似,触发器必须存储在中并

且不能被块进行本地化声明。

对于触发器而言,当触发事件发生的时候就会显式地执行该触发器,并且触发器不

接受参数

 

create table employee(
2>     id          int,
3>     name        nvarchar (10),
4>     salary      int,
5>     start_date  datetime,
6>     city        nvarchar (10),
7>     region      char (1))
8> go
1>
2> insert into employee (id, name,    salary, start_date, city,      

region)
3>               values (1,  'jason', 40420,  '02/01/94', 'new york',

'w')
4> go

(1 rows affected)
1> insert into employee (id, name,    salary, start_date, city,      

region)
2>               values (2,  'robert',14420,  '01/02/95',

'vancouver','n')
3> go

(1 rows affected)
1> insert into employee (id, name,    salary, start_date, city,      

region)
2>               values (3,  'celia', 24020,  '12/03/96', 'toronto', 

'w')
3> go

(1 rows affected)
1> insert into employee (id, name,    salary, start_date, city,      

region)
2>               values (4,  'linda', 40620,  '11/04/97', 'new york',

'n')
3> go

(1 rows affected)
1> insert into employee (id, name,    salary, start_date, city,      

region)
2>               values (5,  'david', 80026,  '10/05/98',

'vancouver','w')
3> go

(1 rows affected)
1> insert into employee (id, name,    salary, start_date, city,      

region)
2>               values (6,  'james', 70060,  '09/06/99', 'toronto', 

'n')
3> go

(1 rows affected)
1> insert into employee (id, name,    salary, start_date, city,      

region)
2>               values (7,  'alison',90620,  '08/07/00', 'new york',

'w')
3> go

(1 rows affected)
1> insert into employee (id, name,    salary, start_date, city,      

region)
2>               values (8,  'chris', 26020,  '07/08/01',

'vancouver','n')
3> go

(1 rows affected)
1> insert into employee (id, name,    salary, start_date, city,      

region)
2>               values (9,  'mary',  60020,  '06/09/02', 'toronto', 

'w')
3> go

(1 rows affected)
1>
2> * from employee
3> go
id          name       salary      start_date              city      

region
----------- ---------- ----------- ----------------------- ---------- -

-----
          1 jason            40420 1994-02-01 00:00:00.000 new york   w
          2 robert           14420 1995-01-02 00:00:00.000 vancouver  n
          3 celia            24020 1996-12-03 00:00:00.000 toronto    w
          4 linda            40620 1997-11-04 00:00:00.000 new york   n
          5 david            80026 1998-10-05 00:00:00.000 vancouver  w
          6 james            70060 1999-09-06 00:00:00.000 toronto    n
          7 alison           90620 2000-08-07 00:00:00.000 new york   w
          8 chris            26020 2001-07-08 00:00:00.000 vancouver  n
          9 mary             60020 2002-06-09 00:00:00.000 toronto    w

(9 rows affected)
1>
2> -- creating and using triggers
3>
4>
5> create trigger mytrigger
6> on employee
7> for update, insert, delete
8> as
9> select * from inserted
10> select * from deleted
11> go
1>
2>
3> select 'before insert'
4> insert employee (id, name) values (31, 'rick')
5> go

-------------
before insert

(1 rows affected)
id          name       salary      start_date              city      

region
----------- ---------- ----------- ----------------------- ---------- -

-----
         31 rick              null                    null null      

null

(1 rows affected)
id          name       salary      start_date              city      

region
----------- ---------- ----------- ----------------------- ---------- -

-----

(0 rows affected)
1>
2> select 'before update'
3> update employee
4> set name = 'rickie'
5> where id = 3
6> go

-------------
before update

(1 rows affected)
id          name       salary      start_date              city      

region
----------- ---------- ----------- ----------------------- ---------- -

-----
          3 rickie           24020 1996-12-03 00:00:00.000 toronto    w

(1 rows affected)
id          name       salary      start_date              city      

region
----------- ---------- ----------- ----------------------- ---------- -

-----
          3 celia            24020 1996-12-03 00:00:00.000 toronto    w

(1 rows affected)
1>
2> select 'before delete'
3> delete from employee where id = 3
4> go

-------------
before delete

(1 rows affected)
id          name       salary      start_date              city      

region
----------- ---------- ----------- ----------------------- ---------- -

-----

(0 rows affected)
id          name       salary      start_date              city      

region
----------- ---------- ----------- ----------------------- ---------- -

-----
          3 rickie           24020 1996-12-03 00:00:00.000 toronto    w

(1 rows affected)
1>
2>
3> drop table employee
4> go
1>

dml触发器的激活顺序

1)执行before语句级触发器—如果存在这种触发器

2)对受该语句影响的每一行记录

执行before行级触发器—如果存在这种触发器

执行该语句本身

执行after行级触发器--如果存在这种触发器

3)执行after语句级触发器--如果存在这种触发器


同一种类型的触发器的点火次序没有经过定义。如果该次序很重要的话,那么建议

将所有这些操作组合到一个触发器当中。


3、行级触发器中的关联标识符

触发器的激活语句每处理一行数据,行级触发器就会激活一次。可以在这种行级触

发器内部,访问正被处理的记录行中的数据。这是通过两个关联标识符--:old

和:new—实现的。关联标识符也是pl/sql的一种特殊的绑定变量。标识符前面的冒

号,既说明这二者都是绑定变量,同时也说明它们不是一般的pl/sql变量。pl/sql

编译器会将它们看作下面这个类型的记录:


triggering_table%rowtype


其中triggering_table是在其上定义触发器的表名。于是,下面这种引用


:new.field


就只有当其中的field是该触发表中的字段名时才会有效。


触发语句
:old
:new

insert
未定义—所有字段均为null
触发语句完成的时候,要插入的值

update
更新以前相应记录行的原始值
触发语句完成的时候,要更新的值

delete
删除以前相应记录行的原始值
未定义—所有字段均为null

 

注意:insert语句上没有定义:old标识符,delete语句上也没有定义:new标识符。

如果再insert语句上使用:old标识符,或者在delete语句上使用:new标识符,

pl/sql并不会产生错误,但是这两个字段值都会为null。


伪记录

虽然在语法构成上,会将:new和:old看作triggering_table%rowtype类型的记录,

但是,实际上它们并不是记录。因此,那些能够在记录上正常执行的操作,并不能

在:new和:old上执行。例如,不能将它们作为一个整体进行赋值。只能对其中的各

个字段分别赋值。

Statement
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
What are stored procedures in MySQL?What are stored procedures in MySQL?May 01, 2025 am 12:27 AM

Stored procedures are precompiled SQL statements in MySQL for improving performance and simplifying complex operations. 1. Improve performance: After the first compilation, subsequent calls do not need to be recompiled. 2. Improve security: Restrict data table access through permission control. 3. Simplify complex operations: combine multiple SQL statements to simplify application layer logic.

How does query caching work in MySQL?How does query caching work in MySQL?May 01, 2025 am 12:26 AM

The working principle of MySQL query cache is to store the results of SELECT query, and when the same query is executed again, the cached results are directly returned. 1) Query cache improves database reading performance and finds cached results through hash values. 2) Simple configuration, set query_cache_type and query_cache_size in MySQL configuration file. 3) Use the SQL_NO_CACHE keyword to disable the cache of specific queries. 4) In high-frequency update environments, query cache may cause performance bottlenecks and needs to be optimized for use through monitoring and adjustment of parameters.

What are the advantages of using MySQL over other relational databases?What are the advantages of using MySQL over other relational databases?May 01, 2025 am 12:18 AM

The reasons why MySQL is widely used in various projects include: 1. High performance and scalability, supporting multiple storage engines; 2. Easy to use and maintain, simple configuration and rich tools; 3. Rich ecosystem, attracting a large number of community and third-party tool support; 4. Cross-platform support, suitable for multiple operating systems.

How do you handle database upgrades in MySQL?How do you handle database upgrades in MySQL?Apr 30, 2025 am 12:28 AM

The steps for upgrading MySQL database include: 1. Backup the database, 2. Stop the current MySQL service, 3. Install the new version of MySQL, 4. Start the new version of MySQL service, 5. Recover the database. Compatibility issues are required during the upgrade process, and advanced tools such as PerconaToolkit can be used for testing and optimization.

What are the different backup strategies you can use for MySQL?What are the different backup strategies you can use for MySQL?Apr 30, 2025 am 12:28 AM

MySQL backup policies include logical backup, physical backup, incremental backup, replication-based backup, and cloud backup. 1. Logical backup uses mysqldump to export database structure and data, which is suitable for small databases and version migrations. 2. Physical backups are fast and comprehensive by copying data files, but require database consistency. 3. Incremental backup uses binary logging to record changes, which is suitable for large databases. 4. Replication-based backup reduces the impact on the production system by backing up from the server. 5. Cloud backups such as AmazonRDS provide automation solutions, but costs and control need to be considered. When selecting a policy, database size, downtime tolerance, recovery time, and recovery point goals should be considered.

What is MySQL clustering?What is MySQL clustering?Apr 30, 2025 am 12:28 AM

MySQLclusteringenhancesdatabaserobustnessandscalabilitybydistributingdataacrossmultiplenodes.ItusestheNDBenginefordatareplicationandfaulttolerance,ensuringhighavailability.Setupinvolvesconfiguringmanagement,data,andSQLnodes,withcarefulmonitoringandpe

How do you optimize database schema design for performance in MySQL?How do you optimize database schema design for performance in MySQL?Apr 30, 2025 am 12:27 AM

Optimizing database schema design in MySQL can improve performance through the following steps: 1. Index optimization: Create indexes on common query columns, balancing the overhead of query and inserting updates. 2. Table structure optimization: Reduce data redundancy through normalization or anti-normalization and improve access efficiency. 3. Data type selection: Use appropriate data types, such as INT instead of VARCHAR, to reduce storage space. 4. Partitioning and sub-table: For large data volumes, use partitioning and sub-table to disperse data to improve query and maintenance efficiency.

How can you optimize MySQL performance?How can you optimize MySQL performance?Apr 30, 2025 am 12:26 AM

TooptimizeMySQLperformance,followthesesteps:1)Implementproperindexingtospeedupqueries,2)UseEXPLAINtoanalyzeandoptimizequeryperformance,3)Adjustserverconfigurationsettingslikeinnodb_buffer_pool_sizeandmax_connections,4)Usepartitioningforlargetablestoi

See all articles

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

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

Dreamweaver Mac version

Dreamweaver Mac version

Visual web development tools

PhpStorm Mac version

PhpStorm Mac version

The latest (2018.2.1) professional PHP integrated development tool

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

Atom editor mac version download

Atom editor mac version download

The most popular open source editor

Safe Exam Browser

Safe Exam Browser

Safe Exam Browser is a secure browser environment for taking online exams securely. This software turns any computer into a secure workstation. It controls access to any utility and prevents students from using unauthorized resources.