Briefly describe the three states of Insert,update,delete within SQL Server triggers

Source: Internet
Author: User
Tags getdate

Three kinds of insert,update,delete states in a trigger

CREATE TRIGGER tr_t_a on t_a for Insert,update,delete

if exists (select * from inserted) and NOT EXISTS (SELECT * from deleted) is an INSERT

if exists (select * from inserted) and exists (SELECT * from deleted) is UPDATE

if exists (select * from deleted) and NOT EXISTS (SELECT * from inserted) is DELETE

Insert Action: Inserted table has data, deleted table has no data

Delete action (delete): Inserted table has no data, deleted table has data

Update: Inserted table has data (new data), deleted table has data (old data)

The author uses the case:

Create TRIGGER [risk]. [Entry_head_port_exchange_trigger]

On [RiskH800]. [Risk]. [Entry_head]

After Insert,update

As

DECLARE @COUNT INT

DECLARE @MANUAL_NO_COUNT INT

IF EXISTS (SELECT 1 from INSERTED)

IF EXISTS (SELECT 1 from DELETED)

BEGIN

SELECT @COUNT = COUNT (*) from risk. Entry_head_port_exchange WHERE entry_id = (select entry_id from DELETED)

SELECT @MANUAL_NO_COUNT = COUNT (manual_no) from DELETED where substring (manual_no,1,1) = ' B ' or substring (manual_no,1,1) = C

IF @COUNT <=0 and @MANUAL_NO_COUNT >0

INSERT into risk. Entry_head_port_exchange (entry_id,create_date) (SELECT entry_id,getdate () from DELETED)

End

ELSE

BEGIN

SELECT @COUNT = COUNT (*) from risk. Entry_head_port_exchange WHERE entry_id = (select entry_id from INSERTED)

SELECT @MANUAL_NO_COUNT = COUNT (manual_no) from INSERTED where substring (manual_no,1,1) = ' B ' or substring (manual_no,1,1) = ' C '

IF @COUNT <=0 and @MANUAL_NO_COUNT >0

INSERT into risk. Entry_head_port_exchange (entry_id,create_date) (SELECT entry_id,getdate () from INSERTED)

End

Related Article

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.