Determines whether the trigger is processing insert, delete, or update.

Source: Internet
Author: User
Generally, TRIGGER is written. INSERT, DELETE, and UPDATE are written separately.

Generally, TRIGGER is written. INSERT, DELETE, and UPDATE are written separately.

However, sometimes, you can view the logic of the process and write the three into a trigger, only to make a slight judgment.

You can determine from the following method whether the trigger is triggered by processing the insert, delete, or update:

The Code is as follows:
-- Declare two variables
DECLARE @ d bit = 0
DECLARE @ I BIT = 0

-- If a record is found in the temporary trigger table of DELETED, the old data is DELETED.
If exists (select top 1 1 from deleted)
SET @ D = 1

-- If a record is found in the temporary trigger table of INSERTED, new data is INSERTED.
If exists (select top 1 1 from inserted)
SET @ I = 1

-- If both tables have records, the trigger is triggered by an update.
IF @ I = 1 AND @ D = 1
PRINT (n' update. ')

-- If the variable @ I is changed to 1, and the variable @ D is not changed, the trigger is triggered by executing the insert operation.
IF @ I = 1 AND @ D = 0
PRINT (n'insert ')

-- The following judgment is true, indicating that the trigger is triggered when the deletion is executed.
IF @ I = 0 AND @ D = 1
PRINT (n'delete ')


In addition, there are two temporary internal trigger tables, the Inserted Table of the trigger and the Deleted table.

The trigger has two virtual tables: The Inserted Table and the Deleted table. The two tables have different data statuses under different operations.
1. INSERT: The Inserted Table has data, and the Deleted table has no data.
2. UPDATE: The Inserted Table has data (new data) and the Deleted table has data (old data ).
Iii. DELETE: The Inserted Table has no data and the 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.