Tuesday, September 4, 2012

Sql Triggers

As a simple definition we can say that
" A trigger is a database object that is attached to a table"

Triggers is  only fired when an INSERT, UPDATE or DELETE occurs in any Data base table.We specify the action to fired the trigger. As per example.

SET NOCOUNT ON

CREATE TABLE Student (St_ID int IDENTITY, St_Desc varchar(10))
go
CREATE TRIGGER tr_Source_INSERT
ON Student
FOR INSERT
AS
PRINT GETDATE()
go
INSERT Student (St_Desc) VALUES ('Test 1')

-- Results --

Apr 28 2001  9:56AM
 
Another example of triggers will be clear the idea.
 
CREATE TABLE Orders (Ord_ID int IDENTITY, Ord_Priority varchar(10))
go
CREATE TRIGGER tr_Orders_INSERT
ON Orders
FOR INSERT
AS
IF (SELECT COUNT(*) FROM inserted WHERE Ord_Priority = 'High') = 1
 BEGIN
  PRINT 'Email Code Goes Here'
 END
go
INSERT Orders (Ord_Priority) VALUES ('High')

-- Results --

Email Code Goes Here 

Triggers make use of two special tables called inserted and deleted.
 The inserted table contains the data referenced in an INSERT before it 
is actually committed to the database. The deleted table contains the 
data in the underlying table referenced in a DELETE before it is 
actually removed from the database. When an UPDATE is issued both tables
 are used. More specifically, the new data referenced in the UPDATE statement is contained in inserted and the data that is being updated is contained in deleted.

No comments:

Post a Comment