search
HomeDatabaseMysql TutorialSQL SERVER 触发器介绍

触发器是一种特殊类型的存储过程,它不同于之前的我们介绍的存储过程。触发器主要是通过事件进行触发被自动调用执行的。而存储过程可以通过存储过程的名称被调用。

Ø 什么是触发器

触发器对表进行插入、更新、删除的时候会自动执行的特殊存储过程。触发器一般用在check约束更加复杂的约束上面。触发器和普通的存储过程的区别是:触发器是当对某一个表进行操作。诸如:update、insert、delete这些操作的时候,系统会自动调用执行该表上对应的触发器。SQL Server 2005中触发器可以分为两类:DML触发器和DDL触发器,其中DDL触发器它们会影响多种数据定义语言语句而激发,这些语句有create、alter、drop语句。

DML触发器分为:

1、 after触发器(之后触发)

a、 insert触发器

b、 update触发器

c、 delete触发器

2、 instead of 触发器 (之前触发)

其中after触发器要求只有执行某一操作insert、update、delete之后触发器才被触发,且只能定义在表上。而instead of触发器表示并不执行其定义的操作(insert、update、delete)而仅是执行触发器本身。既可以在表上定义instead of触发器,也可以在视图上定义。

触发器有两个特殊的表:插入表(instered表)和删除表(deleted表)。这两张是逻辑表也是虚表。有系统在内存中创建者两张表,不会存储在数据库中。而且两张表的都是只读的,只能读取数据而不能修改数据。这两张表的结果总是与被改触发器应用的表的结构相同。当触发器完成工作后,这两张表就会被删除。Inserted表的数据是插入或是修改后的数据,而deleted表的数据是更新前的或是删除的数据。

Update数据的时候就是先删除表记录,然后增加一条记录。这样在inserted和deleted表就都有update后的数据记录了。注意的是:触发器本身就是一个事务,所以在触发器里面可以对修改数据进行一些特殊的检查。如果不满足可以利用事务回滚,撤销操作。

Ø 创建触发器

语法

  tgr_name<br> table_name<br> encrypion –加密触发器<br>   ...<br><br>  Transact-SQL

# 创建insert类型触发器

--创建insert插入类型触发器<br> (object_id(, )   )<br>    tgr_classes_insert<br><br>  tgr_classes_insert<br> classes<br>   insert --插入触发<br><br>  --定义变量<br>   @id , @name (20), @temp ;<br>  --在inserted表中查询已经插入记录信息<br>   @id = id, @name = name  inserted;<br>   @name = @name + (, @id);<br>   @temp = @id / 2;  <br>  insert  student (@name, 18 + @id, @temp, @id);<br>   ;<br><br>--插入数据<br>insert  classes (, getDate());<br>--查询数据<br> *  classes;<br> *  student   id;

insert触发器,会在inserted表中添加一条刚插入的记录。

# 创建delete类型触发器

--delete删除类型触发器<br> (object_id(, )   )<br>    tgr_classes_delete<br><br>  tgr_classes_delete<br> classes<br>    --删除触发<br><br>   ;  <br>   (object_id(, )   )<br>    --存在classesBackup,直接插入数据<br>    insert  classesBackup  name, createDate  deleted;<br>  <br>    --不存在classesBackup创建再插入<br>     *  classesBackup  deleted;<br>   ;<br><br><br><br>-- nocount ;<br> classes  name = ;<br>--查询数据<br> *  classes;<br> *  classesBackup;

delete触发器会在删除数据的时候,将刚才删除的数据保存在deleted表中。

# 创建update类型触发器

--update更新类型触发器<br> (object_id(, )   )<br>    tgr_classes_update<br><br>  tgr_classes_update<br> classes<br>   <br><br>   @oldName (20), @newName (20);<br>  --更新前的数据<br>   @oldName = name  deleted;<br>   ( ( *  student  name  + @oldName + ))<br>    <br>      --更新后的数据<br>       @newName = name  inserted;<br>       student  name = replace(name, @oldName, @newName)  name  + @oldName + ;<br>       ;<br>    <br>  <br>     ;<br><br>--查询数据<br> *  student   id;<br> *  classes;<br> classes  name =   name = ;

update触发器会在更新数据后,将更新前的数据保存在deleted表中,更新后的数据保存在inserted表中。

# update更新列级触发器

 (object_id(, )   )<br>    tgr_classes_update_column<br><br>  tgr_classes_update_column<br> classes<br>   <br><br>  --列级触发器:是否更新了班级创建时间<br>   ((createDate))<br>  <br>    (, 16, 11);<br>     ;<br>  <br><br>--测试<br> *  student   id;<br> *  classes;<br> classes  createDate = getDate()  id = 3;<br> classes  name =   id = 7;

更新列级触发器可以用update是否判断更新列记录;

# instead of类型触发器

instead of触发器表示并不执行其定义的操作(insert、update、delete)而仅是执行触发器本身的内容。

创建语法

  tgr_name<br> table_name<br> encryption<br>  instead  ...<br><br>  T-SQL

# 创建instead of触发器

 (object_id(, )   )<br>    tgr_classes_inteadOf<br><br>  tgr_classes_inteadOf<br> classes<br>  instead  <br><br>   @id , @name (20);<br>  --查询被删除的信息,病赋值<br>   @id = id, @name = name  deleted;<br>    + (, @id) +  + @name;<br>  --先删除student的信息<br>   student  cid = @id;<br>  --再删除classes的信息<br>   classes  id = @id;<br>    + (, @id) +  + @name + ;<br><br>--test<br> *  student   id;<br> *  classes;<br> classes  id = 7;

# 显示自定义消息raiserror

 (object_id(, )   )<br>    tgr_message<br><br>  tgr_message<br> student<br>   insert, <br> (, 16, 10);<br><br>--test<br>insert  student (, 22, 1, 7);<br> student  sex = 0  name = ;<br> *  student   id;

# 修改触发器

  tgr_message<br> student<br> <br> (, 16, 10);<br><br>--test<br>  student  name = ;

# 启用、禁用触发器

--禁用触发器<br>disable  tgr_message  student;<br>--启用触发器<br>enable  tgr_message  student;

# 查询创建的触发器信息

--查询已存在的触发器<br> *  sys.triggers;<br> *  sys.objects  type = ;<br><br>--查看触发器触发事件<br> te.*  sys.trigger_events te  sys.triggers t<br> t.object_id = te.object_id<br> t.parent_class = 0  t.name = ;<br><br>--查看创建触发器语句<br> sp_helptext ;
# 示例,验证插入数据
 ((object_id(, )   ))<br>    tgr_valid_data<br><br>  tgr_valid_data<br> student<br> insert<br><br>   @age ,<br>      @name (20);<br>   @name = s.name, @age = s.age  inserted s;<br>   (@age   <br>    (, 16, 1);<br>     ;<br>  <br><br>--test<br>insert  student (, 2, 0, 7);<br>insert  student (, 22, 0, 7);<br> *  student   id;

# 示例,操作日志

(object_id(, ) )
log

log(
id (1, 1) ,
(20),
createDate datetime getDate()
)

( ( * sys.objects name = ))
tgr_student_log

tgr_student_log
student
insert, ,

(( ( 1 inserted)) ( ( 1 deleted)))

insert log() ();

( ( 1 inserted) ( 1 deleted))

insert log() ();

( ( 1 inserted) ( 1 deleted))

insert log() ();


--test
insert student (, 22, 1, 7);
student sex = 0 name = ;
student name = ;
* log;
* student id;

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
MySQL's Place: Databases and ProgrammingMySQL's Place: Databases and ProgrammingApr 13, 2025 am 12:18 AM

MySQL's position in databases and programming is very important. It is an open source relational database management system that is widely used in various application scenarios. 1) MySQL provides efficient data storage, organization and retrieval functions, supporting Web, mobile and enterprise-level systems. 2) It uses a client-server architecture, supports multiple storage engines and index optimization. 3) Basic usages include creating tables and inserting data, and advanced usages involve multi-table JOINs and complex queries. 4) Frequently asked questions such as SQL syntax errors and performance issues can be debugged through the EXPLAIN command and slow query log. 5) Performance optimization methods include rational use of indexes, optimized query and use of caches. Best practices include using transactions and PreparedStatemen

MySQL: From Small Businesses to Large EnterprisesMySQL: From Small Businesses to Large EnterprisesApr 13, 2025 am 12:17 AM

MySQL is suitable for small and large enterprises. 1) Small businesses can use MySQL for basic data management, such as storing customer information. 2) Large enterprises can use MySQL to process massive data and complex business logic to optimize query performance and transaction processing.

What are phantom reads and how does InnoDB prevent them (Next-Key Locking)?What are phantom reads and how does InnoDB prevent them (Next-Key Locking)?Apr 13, 2025 am 12:16 AM

InnoDB effectively prevents phantom reading through Next-KeyLocking mechanism. 1) Next-KeyLocking combines row lock and gap lock to lock records and their gaps to prevent new records from being inserted. 2) In practical applications, by optimizing query and adjusting isolation levels, lock competition can be reduced and concurrency performance can be improved.

MySQL: Not a Programming Language, But...MySQL: Not a Programming Language, But...Apr 13, 2025 am 12:03 AM

MySQL is not a programming language, but its query language SQL has the characteristics of a programming language: 1. SQL supports conditional judgment, loops and variable operations; 2. Through stored procedures, triggers and functions, users can perform complex logical operations in the database.

MySQL: An Introduction to the World's Most Popular DatabaseMySQL: An Introduction to the World's Most Popular DatabaseApr 12, 2025 am 12:18 AM

MySQL is an open source relational database management system, mainly used to store and retrieve data quickly and reliably. Its working principle includes client requests, query resolution, execution of queries and return results. Examples of usage include creating tables, inserting and querying data, and advanced features such as JOIN operations. Common errors involve SQL syntax, data types, and permissions, and optimization suggestions include the use of indexes, optimized queries, and partitioning of tables.

The Importance of MySQL: Data Storage and ManagementThe Importance of MySQL: Data Storage and ManagementApr 12, 2025 am 12:18 AM

MySQL is an open source relational database management system suitable for data storage, management, query and security. 1. It supports a variety of operating systems and is widely used in Web applications and other fields. 2. Through the client-server architecture and different storage engines, MySQL processes data efficiently. 3. Basic usage includes creating databases and tables, inserting, querying and updating data. 4. Advanced usage involves complex queries and stored procedures. 5. Common errors can be debugged through the EXPLAIN statement. 6. Performance optimization includes the rational use of indexes and optimized query statements.

Why Use MySQL? Benefits and AdvantagesWhy Use MySQL? Benefits and AdvantagesApr 12, 2025 am 12:17 AM

MySQL is chosen for its performance, reliability, ease of use, and community support. 1.MySQL provides efficient data storage and retrieval functions, supporting multiple data types and advanced query operations. 2. Adopt client-server architecture and multiple storage engines to support transaction and query optimization. 3. Easy to use, supports a variety of operating systems and programming languages. 4. Have strong community support and provide rich resources and solutions.

Describe InnoDB locking mechanisms (shared locks, exclusive locks, intention locks, record locks, gap locks, next-key locks).Describe InnoDB locking mechanisms (shared locks, exclusive locks, intention locks, record locks, gap locks, next-key locks).Apr 12, 2025 am 12:16 AM

InnoDB's lock mechanisms include shared locks, exclusive locks, intention locks, record locks, gap locks and next key locks. 1. Shared lock allows transactions to read data without preventing other transactions from reading. 2. Exclusive lock prevents other transactions from reading and modifying data. 3. Intention lock optimizes lock efficiency. 4. Record lock lock index record. 5. Gap lock locks index recording gap. 6. The next key lock is a combination of record lock and gap lock to ensure data consistency.

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

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)
3 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Best Graphic Settings
3 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. How to Fix Audio if You Can't Hear Anyone
3 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
WWE 2K25: How To Unlock Everything In MyRise
4 weeks agoBy尊渡假赌尊渡假赌尊渡假赌

Hot Tools

Atom editor mac version download

Atom editor mac version download

The most popular open source editor

ZendStudio 13.5.1 Mac

ZendStudio 13.5.1 Mac

Powerful PHP integrated development environment

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

WebStorm Mac version

WebStorm Mac version

Useful JavaScript development tools

VSCode Windows 64-bit Download

VSCode Windows 64-bit Download

A free and powerful IDE editor launched by Microsoft