Instead Of Trigger in SQL Server 2005

Monday, March 23, 2009 |

As name said “Instead Of” when you submit any transaction, “Instead of” trigger get fire first instead of your submitted DML processes further. You can define only one “Instead Of” Trigger for one table or one view.

--create table for demo

CREATE TABLE empData

(

Name varchar(10),

Age INT

)


--create INSTEAD OF trigger on empData table,

--which will show message if Age > 100

--and roll back transaction

alter TRIGGER empAgeCheck ON empData

INSTEAD OF INSERT

AS

SET NOCOUNT ON

DECLARE @Age INT

SELECT @Age=Age FROM INSERTED

IF (@Age>100)

BEGIN

print 'you can not do this'

ROLLBACK

END

GO


--try inserting records and see message

INSERT INTO empData VALUES('TestName',101)


--finally check your data in empData table.

select * from empData

Reference: Ritesh Shah
http://www.sqlhub.com
Note: Microsoft Books online is a default reference of all articles but examples and explanations prepared by Ritesh Shah, founder of
http://www.SQLHub.com

2 comments:

sandeep kumar srivastava said...

What about empdata table. Now row inserted in this ?

Ritesh Shah said...

no, row will not be inserted, have you checked the example I saw?