A trigger is a database code that executes automatically when a specific event (insert, update, delete) occurs. The trigger syntax includes trigger name, table name, triggering time (BEFORE/AFTER) and event type (INSERT/UPDATE/DELETE). Trigger types include BEFORE and AFTER, and event types include INSERT, UPDATE, and DELETE. Triggers can be used for data integrity verification, audit logging, automated tasks, and business logic. For example, you can create a trigger to record the insertion time when a new row is inserted to ensure data consistency.
SQL trigger usage and syntax
What is a trigger?
A trigger is a piece of code in the database that automatically triggers execution when a specific event occurs in the database. They are used to perform custom actions when data changes.
The syntax of triggers
The syntax of triggers in SQL is as follows:
<code>CREATE TRIGGER trigger_name ON table_name FOR INSERT | UPDATE | DELETE AS BEGIN -- 触发器代码... END;</code>
Types of triggers
According to the triggering timing, triggers can be divided into the following types:
BEFORE
Trigger: executed before the event occurs. AFTER
Trigger: executed after the event occurs. According to the event type, triggers can be divided into:
INSERT
Trigger: triggered when a new row is inserted. UPDATE
Trigger: Fires when an existing row is updated. DELETE
Trigger: Fires when a row is deleted. Usage scenarios of triggers
Triggers are widely used in the following scenarios:
Example
The following is an example trigger that logs the insertion time when a new row is inserted into the users
table:
<code class="sql">CREATE TRIGGER insert_timestamp BEFORE INSERT ON users AS BEGIN SET NEW.created_at = CURRENT_TIMESTAMP(); END;</code>
When inserting a new row into the users
table, the insert_timestamp
trigger will be executed before the insertion and automatically set the current timestamp to the ## of the new row. #created_at field.
The above is the detailed content of The use and syntax of sql triggers. For more information, please follow other related articles on the PHP Chinese website!