SQL Server create TRIGGER, Update table

Source: Internet
Author: User

In SQL Server, trigger, INSERT, UPDATE, delete state:

CREATE TRIGGER t_inms_alarms

On [PHS]. [dbo]. [Alarmcurrent]

For INSERT, DELETE

As

DECLARE @rows int

SELECT @rows = @ @rowcount

IF @rows = 0

Return

--If the table is inserted, synchronize the update alarmsmiddletbl

IF EXISTS (select 1 from inserted) and not EXISTS (select 1 from deleted)

BEGIN

INSERT into [PHS]. [dbo]. [ALARMSMIDDLETBL]

SELECT I.[id], I.[sequenceid], I.[code], I.[alarmdefineid],

CONVERT (varchar,i.[occurtime],120), i.[confirmation], I.[confirmationtime],

I.[maintenancename], I.[maintenanceprocedure],

I.[cleartime], i.[screen],convert (varchar, GETDATE (), 120)

From inserted I

END

--If the table is updating a field, synchronize the update alarmsmiddletbl

IF not EXISTS (select 1 from inserted) and EXISTS (select 1 from deleted) and

UPDATE (Confirmationtime)

BEGIN

INSERT into [PHS]. [dbo]. [ALARMSMIDDLETBL]

SELECT D.[id], D.[sequenceid], D.[code], D.[alarmdefineid],

CONVERT (varchar,d.[occurtime],120), d.[confirmation], D.[confirmationtime],

D.[maintenancename], D.[maintenanceprocedure],

CONVERT (varchar, GETDATE (), +), d.[screen],convert (varchar, GETDATE (), 120)

From deleted D

END

--If the table is deleted, synchronize the update alarmsmiddletbl

IF not EXISTS (select 1 from inserted) and EXISTS (select 1 from deleted)

BEGIN

INSERT into [PHS]. [dbo]. [ALARMSMIDDLETBL]

SELECT D.[id], D.[sequenceid], D.[code], D.[alarmdefineid],

CONVERT (varchar,d.[occurtime],120), d.[confirmation], D.[confirmationtime],

D.[maintenancename], D.[maintenanceprocedure],

CONVERT (varchar, GETDATE (), +), d.[screen],convert (varchar, GETDATE (), 120)

From deleted D

END

IF @ @error <> 0

BEGIN

RAISERROR (' ERROR ', 16, 1)

ROLLBACK TRANSACTION

Return

END

SQL Server create TRIGGER, Update table

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.