Guruji Point - Code You Want To Write

  • Home
  • Asp.Net
  • WCF
  • SQL
  • Type Script
  • AngularJS
  • Tech News
  • Blog
  • Earn Online

Wednesday, 20 September 2017

Trigger In SQL Server - Insert Update Delete In Single Trigger With Example

 DML and Trigger, guruji point, Gurujipoint, INsert Update Delete in Trigger, SQL, Trigger in sql     4 comments   


Introduction
In this article we will learn what is trigger . How to manage Insert, Update and Delete operation in trigger. Insert Update and Delete with in Trigger.

Previous Updates
In previous articles we have learnt  Transaction Commit and Rollback in sql server with example.What is Lock and how to achieve lock on sql table. What is Blocking and Deadlock In SQL. Encrypt ConnectionString in Web.config.

What is Trigger
As per Microsoft official defination A trigger is a special kind of stored procedure that automatically executes when an event occurs in the database server. DML triggers execute when a user tries to modify data through a data manipulation language (DML) event. DML events are INSERT, UPDATE, or DELETE statements on a table or view. 

Table Structure

Create Table TestEmployee ( ID INT IDENTITY(1,1) PRIMARY KEY , Name VARCHAR(50), Department VARCHAR(50))

Create Table TestEmployee_History (EmpHistID INT IDENTITY(1,1) PRIMARY KEY, EmpID INT , Name VARCHAR(50), Department VARCHAR(50), ActionType VARCHAR(10))



Trigger For Insert Update Delete
CREATE TRIGGER trg_TestEmployee_IUD ON TestEmployee
AFTER INSERT, UPDATE, DELETE
AS BEGIN

DECLARE  @ID INT,
               @Name VARCHAR(50),
               @Department VARCHAR(50)

---- Get data from inserted/ updated
SELECT @ID= ID,
          @Name = Name,
          @Department = Department
           FROM inserted

 ---- Get data from deleted
              SELECT @ID= ID,
                     @Name = Name,
                     @Department = Department
                    
              FROM deleted

  -- Insert Case
   IF EXISTS( SELECT * FROM inserted) AND NOT EXISTS (SELECT * FROM deleted) 
    BEGIN
             INSERT INTO TestEmployee_History(EmpID, Name, Department, ActionType)
              Values( @ID, @Name, @Department, 'Insert')
    END
    
    -- Update Case
   IF EXISTS( SELECT * FROM inserted) AND EXISTS (SELECT * FROM deleted)
    BEGIN
            INSERT INTO TestEmployee_History(EmpID, Name, Department, ActionType)
              Values( @ID, @Name, @Department, 'Update')
    END
      
       -- Delete Case
       IF EXISTS( SELECT * FROM deleted) AND NOT EXISTS (SELECT * FROM inserted)
       BEGIN
            
         INSERT INTO TestEmployee_History(EmpID, Name, Department, ActionType)
           Values( @ID, @Name, @Department, 'Delete')

       END
END
In this trigger all update insert delete operations of table captured separately . 

Now Insert a Record in TestEmployee table- 




 When you insert a record on TestEmployee table then in message window you will see 1 Row(s) affected two times. This is because of trigger which inserts same record in History table.




 Update a Record in TestEmployee table-
Now Delete a Record in TestEmployee table-

In these images you can easily see the trigger works. On actionType column all three operations recorded.
Hope this article will helpful for you. If any issue then please let us know in comment section.





 
  • Share This:  
  •  Facebook
  •  Twitter
  •  Google+
  •  Stumble
  •  Digg
Email ThisBlogThis!Share to XShare to Facebook
Newer Post Older Post Home
View mobile version

4 comments:

  1. Nelson20 May 2019 at 09:39

    This is a good example for determining which event - INSERT, UPDATE OR DELETE is occurring, but never fetch values into variables, because that assumes only one record is being edited at a time. A trigger must be able to handle a multi-row update, especially since it only executes once PER COMMAND, and not PER RECORD edited.

    ReplyDelete
    Replies
      Reply
  2. EasyITZone8 August 2019 at 02:14

    good example

    ReplyDelete
    Replies
      Reply
  3. Anonymous12 October 2019 at 12:11

    This is a great example, but if you are trying to archive the information, your data source for the delete operation needs to change to the deleted table, otherwise you will simply return null values for any variables set to pull from the original/insert table. Thanks!

    ReplyDelete
    Replies
      Reply
  4. satish kankerwal24 March 2021 at 22:07

    there is bug when update, if i update 2 times then it update previous value

    ReplyDelete
    Replies
      Reply
Add comment
Load more...

Facebook Updates

Guruji Point

Categories

Comman table Expression in SQL Dynamic Grid Row IQueryable in c# Learn AngularJS Scope_Identity() Use of indexes comma seperated string in sql row_number() and dense_rank() salary table structure. while loop in sql why do we need cursor why tuple used

About Us

This blog is about the Programming ,Tech News and some intresting facts related Contents. Here you can find fundamental and expert level topic of programming languages very practically related to C# , Asp.Net ,Sql-Server, JavaScript, Jquery, WebServices And also Web-Api, WCF ,WPF, Angular Js.

Contact Us

Email Us - gurujipoints@gmail.com
Contact- 8077657477

Reach Us

Copyright © Guruji Point - Code You Want To Write