Monday, December 15, 2014

Trigger - a record Update


Refer the source:

Creating a trigger on SQL Server 2008 R2 to catch a record update

 

CREATE TRIGGER  SAMPLETRIGGER

ON SAMPLETABLE

AFTER UPDATE

AS

BEGIN

DECLARE  @INSERTED INT,@DELETED INT

SET @INSERTED = Select Count(*) from Inserted

SET @DELETED = Select Count(*) from Deleted

If @Inserted =1 and @deleted = 1

Begin

Update Table1  set Col1= inserted_col1

where idcol = inserted_idcol

End

End

Note:

1.There isn't an UPDATED pesudo table in TSQL.

2.In a trigger, you get the DELETED and INSERTED tables, there is no UPDATED.

3.Also, it makes sense to add 

IF @@ROWCOUNT=0 RETURN

in the very beginning of trigger's body.When

UPDATE takes place,both inserted and deleted 

tables are not empty.You may add the following code to make sure you handle UPDATE, not insert/delete.

IF EXISTS(Select * FROM INSERTED)  AND

EXISTS(Select * FROM  DELETED)

BEGIN

--handle update

END;

4.We have only two magic tables called INSERTED & DELETED.

Update indirectly is a delete statement followed by Insert statement.So you have to update the columns value which is present in INSERTED.


 





No comments:

Post a Comment