SQL trigger
SQLite trigger (Trigger) is a callback function of the database, which will be automatically executed/called when a specified database event occurs.
Overview
Trigger is a special stored procedure, it cannot be called explicitly, but is automatically activated when inserting records, updating records or deleting records in the table. So triggers can be used to implement complex integrity constraints on the table.
classification
DML trigger
DML (Data Manipulation Language) trigger is a stored procedure that is executed when a data manipulation language event occurs in the database server. It is divided into two parts:
After trigger: This type of trigger is activated and executed after the record has been changed (after). It is mainly used for processing or checking after the record change. Once an error is found, it will also You can use the Rollback Transaction statement to roll back this operation.
Instead Of Trigger: This type of trigger is generally used to replace the original operation, which occurs before the record change, it does not perform the operation (Insert, Update, Delete) in the original SQL statement, but to execute the trigger itself The defined operation.
DDL trigger
DDL triggers are stored procedures that are executed in response to Data Definition Language events. DDL triggers are generally used to perform management tasks in the database. Such as auditing and standardizing database operations, preventing database table structure from being modified, etc.
standard format
CREATE TRIGGER Trigger_Name --触发器名,在一个数据库中触发器名是唯一的。
ON Table_Name | View_Name --触发器所在的表或者视图。
AFTER(FOR)|Instead Of INSERT,DELETE,UPDATE --定义成AFTER或Instead Of类型的触发器。
--AFTER跟FOR相同,不可在视图上定义AFTER触发器
-- 后面是触发器被触发的条件,最少有一个,可以邮多个。如果有多个用逗号分开,顺序无要求。
AS --触发器要执行的操作
BEGIN
--BEGIN跟END组成一个代码块,可以写也可以不写,如果触发器中执行的SQL语句比较复杂,用BEGIN和END会让代码更加整齐,更容易理解。
END
GO --GO就代表结操作完毕