search
HomeDatabaseSQLCommonly used statements of SQL triggers (summary)

This article summarizes some commonly used SQL trigger statements for everyone. It has certain reference value. Friends in need can refer to it. I hope it will be helpful to everyone.

Commonly used statements of SQL triggers (summary)

1. Create a simple trigger

CREATE TRIGGER 触发器名称
ON 表名
FOR INSERT、UPDATE 或 DELETE
AS
    T-SQL 语句

Note: The trigger name is not quoted.

2. Delete triggers

drop trigger 触发器名称

Delete multiple triggers:

drop trigger 触发器名称,触发器名称

3. Rename triggers

Rename with Query Analyzer

exec sp_rename 原名称, 新名称

sp_rename is a stored procedure that comes with SQL Server. It is used to change the names of user-created objects in the current database, such as table names, lists, index names, etc. .

4. INSERT, UPDATE or DELETE

INSTEAD OF

Execute the trigger statement, but do not execute the SQL statement that triggers the trigger, such as trying to When a record is deleted, the statement specified by the trigger will be executed, and the delete statement will no longer be executed at this time. Example:

create trigger f
on tbl
instead of delete
as
    insert into Logs...

IF UPDATE(column name)

Check whether a column has been updated. It is used for insert or update, but cannot be used for delete. Example:

create trigger f
on tbl
for update
as
    if update(status) or update(title)
        sql_statement --更新了 status 或 title 列

inserted, deleted

These are two virtual tables. inserted saves the table formed by the records affected after insert or update, and deleted saves the table formed before delete or update. The table formed by the affected records. Example:

create trigger tbl_delete
on tbl
for delete
as
    declare @title varchar(200)
    select @title=title from deleted
    insert into Logs(logContent) values('删除了 title 为:' + title + '的记录')

Explanation: If the field value of the field type text or image is retrieved from the inserted or deleted virtual table, the obtained value will be null.

5. View all triggers in the database

use 数据库名
go
select * from sysobjects where xtype='TR'
sysobjects 保存着数据库的对象,其中 xtype 为 TR 的记录即为触发器对象。在 name 一列,我们可以看到触发器名称。

6. sp_helptext View trigger content

use 数据库名
go
exec sp_helptext '触发器名称'

7. sp_helptrigger is used to view the attributes of the trigger.

sp_helptrigger has two parameters: the first parameter is the table name; the second parameter is the trigger type, which is char(6) Type, which can be INSERT, UPDATE, or DELETE. If omitted, the properties of all types of triggers in the specified table will be displayed.

Example:

use 数据库名
go
exec sp_helptrigger tbl

8. Recursion, nested triggers

There are two types of recursion, indirect recursion and direct recursion. We explain it with an example as follows. Suppose there are tables 1 and 2 named T1 and T2 respectively, and there are flip-flops G1 and G2 on T1 and T2 respectively.

Indirect recursion: operate on T1 to trigger G1, G1 to operate on T2 to trigger G2, G2 to operate on T1 to trigger G1 again...

Direct recursion: operate on T1 to trigger G1 , G1 operates on T1 to trigger G1 again...

Nested trigger

is similar to indirect recursion. Indirect recursion must form a loop, while nested triggers do not necessarily have to form a loop. A ring can be triggered continuously from T1->T2->T3... in this way, allowing up to 32 levels of nesting.

Set direct recursion

By default, direct recursion is prohibited. There are two methods to set it to allow:

T-SQL: exec sp_dboption 'dbName', ' recursive triggers', true

EM: Right click on the database->Properties->Options.

Set indirect recursion and nesting

By default, indirect recursion and nesting are allowed. There are two ways to disable it:

T-SQL: exec sp_configure 'nested triggers', 0 --The second parameter is 1, which means it is allowed

EM: Right click on the registration->Properties->Server Settings.

9. Trigger rollback

We have seen that many registration systems cannot change the user name after registration, but this is mostly determined by the application. If By directly opening the database table to make changes, you can also change its user name. By using rollback in the trigger, you can cleverly realize that the user name cannot be changed.

use 数据库名
go
create trigger tr
on 表名
for update
as
    if update(userName)
        rollback tran

The key lies in the last two sentences, which are explained as follows: If the userName column is updated, roll back the transaction.

10. Disable and enable triggers

Disable: alter table table name disable trigger trigger name

Enable: alter table table name enable trigger Trigger name

If there are multiple triggers, separate the trigger names with commas.

If you replace "Trigger Name" with "ALL", it means disabling or enabling all triggers of the table.

11. Determine insertion, modification and deletion

create TRIGGER [updatetest] ON [dbo].[TEST] 
FOR INSERT, UPDATE, DELETE 
AS
begin
    DECLARE
    @IsInsert bit,
    @IsUpdate bit,
    @IsDelete bit
    IF EXISTS(SELECT 1 FROM inserted) AND NOT EXISTS(SELECT 1 FROM deleted)
        SET @IsInsert = 1
    ELSE
        SET @IsInsert = 0
     
    IF EXISTS(SELECT 1 FROM inserted) AND EXISTS(SELECT 1 FROM deleted)
        SET @IsUpdate = 1
    ELSE
        SET @IsUpdate = 0
     
    IF NOT EXISTS(SELECT 1 FROM inserted) AND EXISTS(SELECT 1 FROM deleted)
        SET @IsDelete = 1
    ELSE
        SET @IsDelete = 0 
     
    if (@IsUpdate=1)
       PRINT 'updated '
     if (@IsInsert=1)
       PRINT 'insert '
     if (@IsDelete=1)
       PRINT 'delete 'end

Recommended learning: MySQL tutorial

The above is the detailed content of Commonly used statements of SQL triggers (summary). For more information, please follow other related articles on the PHP Chinese website!

Statement
This article is reproduced at:cnblogs. If there is any infringement, please contact admin@php.cn delete
SQL: The Language of Databases ExplainedSQL: The Language of Databases ExplainedApr 27, 2025 am 12:14 AM

SQL is the core tool for database operations, used to query, operate and manage databases. 1) SQL allows CRUD operations to be performed, including data query, operations, definition and control. 2) The working principle of SQL includes three steps: parsing, optimizing and executing. 3) Basic usages include creating tables, inserting, querying, updating and deleting data. 4) Advanced usage covers JOIN, subquery and window functions. 5) Common errors include syntax, logic and performance issues, which can be debugged through database error information, check query logic and use the EXPLAIN command. 6) Performance optimization tips include creating indexes, avoiding SELECT* and using JOIN.

SQL: How to Overcome the Learning HurdlesSQL: How to Overcome the Learning HurdlesApr 26, 2025 am 12:25 AM

To become an SQL expert, you should master the following strategies: 1. Understand the basic concepts of databases, such as tables, rows, columns, and indexes. 2. Learn the core concepts and working principles of SQL, including parsing, optimization and execution processes. 3. Proficient in basic and advanced SQL operations, such as CRUD, complex queries and window functions. 4. Master debugging skills and use the EXPLAIN command to optimize query performance. 5. Overcome learning challenges through practice, utilizing learning resources, attaching importance to performance optimization and maintaining curiosity.

SQL and Databases: A Perfect PartnershipSQL and Databases: A Perfect PartnershipApr 25, 2025 am 12:04 AM

The relationship between SQL and database is closely integrated, and SQL is a tool for managing and operating databases. 1.SQL is a declarative language used for data definition, operation, query and control. 2. The database engine parses SQL statements and executes query plans. 3. Basic usage includes creating tables, inserting and querying data. 4. Advanced usage involves complex queries and subqueries. 5. Common errors include syntax, logic and performance issues, which can be debugged through syntax checking and EXPLAIN commands. 6. Optimization techniques include using indexes, avoiding full table scanning and optimizing queries.

SQL vs. MySQL: Clarifying the Relationship Between the TwoSQL vs. MySQL: Clarifying the Relationship Between the TwoApr 24, 2025 am 12:02 AM

SQL is a standard language for managing relational databases, while MySQL is a database management system that uses SQL. SQL defines ways to interact with a database, including CRUD operations, while MySQL implements the SQL standard and provides additional features such as stored procedures and triggers.

The Importance of SQL: Data Management in the Digital AgeThe Importance of SQL: Data Management in the Digital AgeApr 23, 2025 am 12:01 AM

SQL's role in data management is to efficiently process and analyze data through query, insert, update and delete operations. 1.SQL is a declarative language that allows users to talk to databases in a structured way. 2. Usage examples include basic SELECT queries and advanced JOIN operations. 3. Common errors such as forgetting the WHERE clause or misusing JOIN, you can debug through the EXPLAIN command. 4. Performance optimization involves the use of indexes and following best practices such as code readability and maintainability.

Getting Started with SQL: Essential Concepts and SkillsGetting Started with SQL: Essential Concepts and SkillsApr 22, 2025 am 12:01 AM

SQL is a language used to manage and operate relational databases. 1. Create a table: Use CREATETABLE statements, such as CREATETABLEusers(idINTPRIMARYKEY, nameVARCHAR(100), emailVARCHAR(100)); 2. Insert, update, and delete data: Use INSERTINTO, UPDATE, DELETE statements, such as INSERTINTOusers(id, name, email)VALUES(1,'JohnDoe','john@example.com'); 3. Query data: Use SELECT statements, such as SELEC

SQL: The Language, MySQL: The Database Management SystemSQL: The Language, MySQL: The Database Management SystemApr 21, 2025 am 12:05 AM

The relationship between SQL and MySQL is: SQL is a language used to manage and operate databases, while MySQL is a database management system that supports SQL. 1.SQL allows CRUD operations and advanced queries of data. 2.MySQL provides indexing, transactions and locking mechanisms to improve performance and security. 3. Optimizing MySQL performance requires attention to query optimization, database design and monitoring and maintenance.

What SQL Does: Managing and Manipulating DataWhat SQL Does: Managing and Manipulating DataApr 20, 2025 am 12:02 AM

SQL is used for database management and data operations, and its core functions include CRUD operations, complex queries and optimization strategies. 1) CRUD operation: Use INSERTINTO to create data, SELECT reads data, UPDATE updates data, and DELETE deletes data. 2) Complex query: Process complex data through GROUPBY and HAVING clauses. 3) Optimization strategy: Use indexes, avoid full table scanning, optimize JOIN operations and paging queries to improve performance.

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

PhpStorm Mac version

PhpStorm Mac version

The latest (2018.2.1) professional PHP integrated development tool

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.

EditPlus Chinese cracked version

EditPlus Chinese cracked version

Small size, syntax highlighting, does not support code prompt function

DVWA

DVWA

Damn Vulnerable Web App (DVWA) is a PHP/MySQL web application that is very vulnerable. Its main goals are to be an aid for security professionals to test their skills and tools in a legal environment, to help web developers better understand the process of securing web applications, and to help teachers/students teach/learn in a classroom environment Web application security. The goal of DVWA is to practice some of the most common web vulnerabilities through a simple and straightforward interface, with varying degrees of difficulty. Please note that this software

ZendStudio 13.5.1 Mac

ZendStudio 13.5.1 Mac

Powerful PHP integrated development environment