search
HomeDatabaseMysql TutorialSQL Server 触发器_MySQL

触发器是一种特殊类型的存储过程。

 

触发器和存储过程的区别:触发器主要是通过事件进行触发被自动调用执行的,而存储过程可以通过存储过程的名称被调用。

 

什么是触发器

 

触发器对表进行插入、更新、删除的时候会自动执行的特殊存储过程。触发器一般用在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表的数据是更新前的或是删除的数据。

对表的操作

Inserted逻辑表

Deleted逻辑表

增加记录(insert)

存放增加的记录

删除记录(delete)

存放被删除的记录

修改记录(update)

存放更新后的记录

存放更新前的记录

 

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

 

创建触发器

 

【语法】

 

create trigger tgr_name
on table_name
with encrypion –加密触发器
  for update...
as
   Transact-SQL
   # 创建insert类型触发器

--创建insert插入类型触发器
if (object_id('tgr_classes_insert', 'tr') isnotnull)
droptrigger tgr_classes_insert
go
create trigger tgr_classes_insert
on classes
for insert --插入触发
as
--定义变量
declare @id int, @name varchar(20), @temp int;
--在inserted表中查询已经插入记录信息
  select @id = id, @name = name from inserted;
  set @name = @name + convert(varchar, @id);
  set @temp = @id / 2;
   insert into student values(@name, 18 + @id, @temp, @id);
  print'添加学生成功!';
go
--插入数据
insert into classes values('5班', getDate());
--查询数据
select * from classes;
select * from student orderby id;

 

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

 


# 创建delete类型触发器

--delete删除类型触发器
if (object_id('tgr_classes_delete', 'TR') isnotnull)
droptrigger tgr_classes_delete
go
create trigger tgr_classes_delete
on classes
fordelete --删除触发
as
  print'备份数据中……';
  if (object_id('classesBackup', 'U') isnotnull)
   --存在classesBackup,直接插入数据
   insert into classesBackup select name, createDate from deleted;
  else
   --不存在classesBackup创建再插入
  select * into classesBackup from deleted;
  print'备份数据成功!';
go
--不显示影响行数
--set nocount on;
delete classes where name = '5班';
--查询数据
select * from classes;
select * from classesBackup;

 

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

 

 

   # 创建update类型触发器

--update更新类型触发器
if (object_id('tgr_classes_update', 'TR') isnotnull)
droptrigger tgr_classes_update
go
create  trigger tgr_classes_update
on classes
forupdate
as
  declare @oldName varchar(20), @newName varchar(20);
   --更新前的数据
  select @oldName = name from deleted;
  if (exists (select * from student where name like'%'+ @oldName + '%'))
  begin
   --更新后的数据
  select @newName = name from inserted;
  update student set name = replace(name, @oldName, @newName) where name like'%'+ @oldName + '%';
  print'级联修改数据成功!';
  end
  else
  print'无需修改student表!';
go
--查询数据
select * from student orderby id;
select * from classes;
update classes set name = '五班'where name = '5班';

 

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

 

 

 

# update更新列级触发器

if (object_id('tgr_classes_update_column', 'TR') isnotnull)
droptrigger tgr_classes_update_column
go
create trigger tgr_classes_update_column
on classes
forupdate
as
--列级触发器:是否更新了班级创建时间
  if (update(createDate))
  begin
  raisError('系统提示:班级创建时间不能修改!', 16, 11);
  rollbacktran;
  end
go
--测试
select * from student orderby id;
select * from classes;
update classes set createDate = getDate() where id = 3;
update classes set name = '四班'where id = 7;

 

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

 

 

 

# instead of类型触发器

 

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

 

创建语法

create trigger tgr_name
on table_name
with encryption
instead ofupdate...
as
T-SQL
   

   # 创建instead of触发器

if (object_id('tgr_classes_inteadOf', 'TR') isnotnull)
drop trigger tgr_classes_inteadOf
go
create trigger tgr_classes_inteadOf
on classes
instead ofdelete/*, update, insert*/
as
  declare @id int, @name varchar(20);
--查询被删除的信息,病赋值
  select @id = id, @name = name from deleted;
  print'id: ' + convert(varchar, @id) + ', name: ' + @name;
--先删除student的信息
  delete student where cid = @id;
--再删除classes的信息
  delete classes where id = @id;
  print'删除[ id: ' + convert(varchar, @id) + ', name: ' + @name + ' ] 的信息成功!';
go
--test
select * from student orderby id;
select * from classes;
delete classes where id = 7;
   

  # 显示自定义消息raiserror

if (object_id('tgr_message', 'TR') isnotnull)
drop trigger tgr_message
go
create trigger tgr_message
on student
after insert, update
asraisError('tgr_message触发器被触发', 16, 10);
go
--test
insert into student values('lily', 22, 1, 7);
update student set sex = 0 where name = 'lucy';
select * from student orderby id;
  # 修改触发器

alter trigger tgr_message
on student
after delete
asraisError('tgr_message触发器被触发', 16, 10);
go
--test
deletefrom student where name = 'lucy';
  # 启用、禁用触发器

--禁用触发器
disable trigger tgr_message on student;
--启用触发器
enable trigger tgr_message on student;
   # 查询创建的触发器信息

--查询已存在的触发器
select * from sys.triggers;
select * from sys.objects where type = 'TR';

--查看触发器触发事件
select te.* from sys.trigger_events te join sys.triggers t
on t.object_id = te.object_id
where t.parent_class = 0 and t.name = 'tgr_valid_data';

--查看创建触发器语句
exec sp_helptext 'tgr_message';

  # 示例,验证插入数据

if ((object_id('tgr_valid_data', 'TR') isnotnull))
droptrigger tgr_valid_data
go
createtrigger tgr_valid_data
on student
after insert
as
declare @age int,
@name varchar(20);
select @name = s.name, @age = s.age from inserted s;
if (@age < 18)
begin
raisError(&#39;插入新数据的age有问题&#39;, 16, 1);
rollbacktran;
end
go
--test
insert into student values(&#39;forest&#39;, 2, 0, 7);
insert into student values(&#39;forest&#39;, 22, 0, 7);
select * from student orderby id;
   # 示例,操作日志

if (object_id(&#39;log&#39;, &#39;U&#39;) isnotnull)
droptable log
go
createtable log(
id intidentity(1, 1) primarykey,
actionvarchar(20),
createDate datetime default getDate()
)
go
if (exists (select * from sys.objects where name = &#39;tgr_student_log&#39;))
droptrigger tgr_student_log
go
createtrigger tgr_student_log
on student
after insert, update, delete
as
if ((exists (select 1 from inserted)) and (exists (select 1 from deleted)))
begin
insert into log(action) values(&#39;updated&#39;);
end
elseif (exists (select 1 from inserted) andnotexists (select 1 from deleted))
begin
insert into log(action) values(&#39;inserted&#39;);
end
elseif (notexists (select 1 from inserted) andexists (select 1 from deleted))
begin
insert into log(action) values(&#39;deleted&#39;);
end
go
--test
insert into student values(&#39;king&#39;, 22, 1, 7);
update student set sex = 0 where name = &#39;king&#39;;
delete student where name = &#39;king&#39;;
select * from log;
select * from student orderby 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
Explain the role of InnoDB redo logs and undo logs.Explain the role of InnoDB redo logs and undo logs.Apr 15, 2025 am 12:16 AM

InnoDB uses redologs and undologs to ensure data consistency and reliability. 1.redologs record data page modification to ensure crash recovery and transaction persistence. 2.undologs records the original data value and supports transaction rollback and MVCC.

What are the key metrics to look for in an EXPLAIN output (type, key, rows, Extra)?What are the key metrics to look for in an EXPLAIN output (type, key, rows, Extra)?Apr 15, 2025 am 12:15 AM

Key metrics for EXPLAIN commands include type, key, rows, and Extra. 1) The type reflects the access type of the query. The higher the value, the higher the efficiency, such as const is better than ALL. 2) The key displays the index used, and NULL indicates no index. 3) rows estimates the number of scanned rows, affecting query performance. 4) Extra provides additional information, such as Usingfilesort prompts that it needs to be optimized.

What is the Using temporary status in EXPLAIN and how to avoid it?What is the Using temporary status in EXPLAIN and how to avoid it?Apr 15, 2025 am 12:14 AM

Usingtemporary indicates that the need to create temporary tables in MySQL queries, which are commonly found in ORDERBY using DISTINCT, GROUPBY, or non-indexed columns. You can avoid the occurrence of indexes and rewrite queries and improve query performance. Specifically, when Usingtemporary appears in EXPLAIN output, it means that MySQL needs to create temporary tables to handle queries. This usually occurs when: 1) deduplication or grouping when using DISTINCT or GROUPBY; 2) sort when ORDERBY contains non-index columns; 3) use complex subquery or join operations. Optimization methods include: 1) ORDERBY and GROUPB

Describe the different SQL transaction isolation levels (Read Uncommitted, Read Committed, Repeatable Read, Serializable) and their implications in MySQL/InnoDB.Describe the different SQL transaction isolation levels (Read Uncommitted, Read Committed, Repeatable Read, Serializable) and their implications in MySQL/InnoDB.Apr 15, 2025 am 12:11 AM

MySQL/InnoDB supports four transaction isolation levels: ReadUncommitted, ReadCommitted, RepeatableRead and Serializable. 1.ReadUncommitted allows reading of uncommitted data, which may cause dirty reading. 2. ReadCommitted avoids dirty reading, but non-repeatable reading may occur. 3.RepeatableRead is the default level, avoiding dirty reading and non-repeatable reading, but phantom reading may occur. 4. Serializable avoids all concurrency problems but reduces concurrency. Choosing the appropriate isolation level requires balancing data consistency and performance requirements.

MySQL vs. Other Databases: Comparing the OptionsMySQL vs. Other Databases: Comparing the OptionsApr 15, 2025 am 12:08 AM

MySQL is suitable for web applications and content management systems and is popular for its open source, high performance and ease of use. 1) Compared with PostgreSQL, MySQL performs better in simple queries and high concurrent read operations. 2) Compared with Oracle, MySQL is more popular among small and medium-sized enterprises because of its open source and low cost. 3) Compared with Microsoft SQL Server, MySQL is more suitable for cross-platform applications. 4) Unlike MongoDB, MySQL is more suitable for structured data and transaction processing.

How does MySQL index cardinality affect query performance?How does MySQL index cardinality affect query performance?Apr 14, 2025 am 12:18 AM

MySQL index cardinality has a significant impact on query performance: 1. High cardinality index can more effectively narrow the data range and improve query efficiency; 2. Low cardinality index may lead to full table scanning and reduce query performance; 3. In joint index, high cardinality sequences should be placed in front to optimize query.

MySQL: Resources and Tutorials for New UsersMySQL: Resources and Tutorials for New UsersApr 14, 2025 am 12:16 AM

The MySQL learning path includes basic knowledge, core concepts, usage examples, and optimization techniques. 1) Understand basic concepts such as tables, rows, columns, and SQL queries. 2) Learn the definition, working principles and advantages of MySQL. 3) Master basic CRUD operations and advanced usage, such as indexes and stored procedures. 4) Familiar with common error debugging and performance optimization suggestions, such as rational use of indexes and optimization queries. Through these steps, you will have a full grasp of the use and optimization of MySQL.

Real-World MySQL: Examples and Use CasesReal-World MySQL: Examples and Use CasesApr 14, 2025 am 12:15 AM

MySQL's real-world applications include basic database design and complex query optimization. 1) Basic usage: used to store and manage user data, such as inserting, querying, updating and deleting user information. 2) Advanced usage: Handle complex business logic, such as order and inventory management of e-commerce platforms. 3) Performance optimization: Improve performance by rationally using indexes, partition tables and query caches.

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

Hot Tools

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

SAP NetWeaver Server Adapter for Eclipse

SAP NetWeaver Server Adapter for Eclipse

Integrate Eclipse with SAP NetWeaver application server.

Dreamweaver Mac version

Dreamweaver Mac version

Visual web development tools

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.

MinGW - Minimalist GNU for Windows

MinGW - Minimalist GNU for Windows

This project is in the process of being migrated to osdn.net/projects/mingw, you can continue to follow us there. MinGW: A native Windows port of the GNU Compiler Collection (GCC), freely distributable import libraries and header files for building native Windows applications; includes extensions to the MSVC runtime to support C99 functionality. All MinGW software can run on 64-bit Windows platforms.