Atlanta Custom Software Development 

 
   Search        Code/Page
 

User Login
Email

Password

 

Forgot the Password?
Services
» Web Development
» Maintenance
» Data Integration/BI
» Information Management
Programming
  Database
Automation
OS/Networking
Graphics
Links
Tools
» Regular Expr Tester
» Free Tools

How to write a trigger for INSERT, UPDATE or DELETE operation ?

Total Hit ( 2335)

Rate this article:     Poor     Excellent 

 Submit Your Question/Comment about this article

Rating


 


Here is very basic code to write trigger for INSERT, UPDATE or DELETE operation on a table. Internally SQL Server manages two tables (inserted and deleted) to perform trigger operations.

All inserted records can be retrived by quering "inserted" table

Click here to copy the following block
select * from inserted

All deleted records can be retrived by quering "deleted" table

Click here to copy the following block
select * from deleted

All updated records can be retrived by joining with inserted and deleted tables. Since there is no seperate table named "updated" for updated records so you have to find updated records by joining "inserted" and "deleted" tables

Click here to copy the following block
SELECT i.*
FROM  inserted i
INNER JOIN deleted d
   ON i.ProductID = d.ProductID


Click here to copy the following block
set nocount on
go
if object_id('tr_tbl') is not null
   drop table tr_tbl
go
create table tr_tbl(i int)
go
create trigger tr_test on tr_tbl for insert, update, delete as
if exists(select * from inserted) and exists(select * from deleted)
   print 'Update...'
else
if exists(select * from inserted)
   print 'Insert...'
else
   print 'Delete...'
go

insert tr_tbl values(1)
update tr_tbl set i = i + 1
delete tr_tbl


Submitted By : Nayan Patel  (Member Since : 5/26/2004 12:23:06 PM)

Job Description : He is the moderator of this site and currently working as an independent consultant. He works with VB.net/ASP.net, SQL Server and other MS technologies. He is MCSD.net, MCDBA and MCSE. In his free time he likes to watch funny movies and doing oil painting.
View all (893) submissions by this author  (Birth Date : 7/14/1981 )


Home   |  Comment   |  Contact Us   |  Privacy Policy   |  Terms & Conditions   |  BlogsZappySys

© 2008 BinaryWorld LLC. All rights reserved.