To determine whether the trigger is processing an INSERT, delete, or UPDATE trigger _mssql

Source: Internet
Author: User
But sometimes, you can see the logic level, you can write the three triggers, just a little judgment.

You can determine whether a trigger is handled by inserting, deleting, or updating according to the following methods:

Copy Code code as follows:

--Declaring two variables
DECLARE @D BIT = 0
DECLARE @i BIT = 0

--If a record is found inside the deleted temporary touch, the old data is deleted
IF EXISTS (SELECT top 1 1 DELETED)
SET @D = 1

--If a record is found inside the inserted, the new data is inserted
IF EXISTS (SELECT top 1 1 INSERTED)
SET @i = 1

--If all two tables have records, the trigger is a trigger that performs an update
IF @i = 1 and @D = 1
PRINT (N ' update. ')

--If the variable @i value is changed to 1, and the variable @d is not changed, the trigger is to execute the INSERT trigger
IF @i = 1 and @D = 0
PRINT (N ' Insert ')

--The following judgment is set up to indicate that the trigger is executing the DELETE trigger
IF @i = 0 and @D = 1
PRINT (N ' delete ')


In addition the inserted table and deleted table about two internal temporary contacts are published, triggers

Triggers have two virtual tables, inserted tables, and deleted tables, which have different data states in the table under various operating conditions.
First, insert operation (INSERT): Inserted table has data, deleted table no data.
Second, update operation (UPDATE): Inserted table has data (new data), deleted table has data (old data).
Third, delete operation (delete): Inserted table no data, deleted table has data.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.