Instead of Update Trigger in SQL Server


Instead of Update Trigger

To Create INSTEAD OF UPDATE Triggers first of all we need to create a table (but we create two table) for which we apply trigger and need another table that hold all activity in main table.
-- We create tblDeparment

create table tblDeparment(
Id int identity(1,1) primary key not null,
DeparmentName varchar(30) not null,
Location Char(8) not null,
DeparmentHead varchar(20) not null
)

--Insert data into tblDeparment

Insert into tblDeparment values('IT','London','Carrie')
Insert into tblDeparment values('HR','Mexico','Toy')
Insert into tblDeparment values('Purchasing','Delhi','Ravi')
Insert into tblDeparment values('Finance','New York','Janie')

--Now crate table tblEmployee

create table tblEmployee(
Id int identity(1,1) primary key not null,
Name varchar(30) not null,
Gender Char(8) not null,
DeparmentId int null constraint FK_tblEmployee_DeparmentId foreign key(DeparmentId) references tblDeparment(Id)
)

--Insert data into tblEmployee 

insert into tblEmployee values('Jane', 'Female', 1) 
insert into tblEmployee values('Levis', 'Male', 3)
insert into tblEmployee values('Lee', 'Female', Null)
insert into tblEmployee values('Rose', 'Female', 1)
Here we create two table “tblDeparment” and “tblEmployee “ which are inter-connected through Foreign key constraint.

We will apply trigger for these tables.

Now create table that hold activity of main table by user.
create table tblAudit
(
Id int primary key identity(1,1) not null,
AuditData nvarchar(500)
) 
We have table are given below with data.
instead-of-update-triggers
Created All tables for Instead of Update Triggers

Now create the INSTEAD OF UPDATE Trigger for “tblEmployee”.
create trigger trtblEmployeeInsteadOfUpdate
on tblEmployee
INSTEAD OF update
AS
  BEGIN
     Declare @EmpId int,               
             @EmpMessage varchar(200),
             @Name varchar(30), @Gender varchar(8),
             @DepartmentId int;
     select  @EmpId =D.Id 
             from deleted D;
     select  @Name = I.Name, 
             @Gender = I.Gender,
             @DepartmentId= DeparmentId from Inserted I;
             
      
     If(Not exists(Select Id from tblEmployee where Id = @EmpId))   --If Id not Exists in Cloumn than through message. you can check other condition like departmentId =1 or Gender=Male, than you can print message you can not delete
       Begin
           SET @EmpMessage  = 'Employee With Id ' + CAST(@EmpId as varchar(5)) + 'Not Exists in the DataBase'
           Raiserror(@EmpMessage, 16, 1)
           Print 'Employee Not Exists'
           RollBack
       End
       Else
          Begin
            if(UPDATE(Name))
              begin
                 update tblEmployee set Name = @Name where Id= @EmpId
              end
             If(UPDATE(Gender))
               begin
                 update tblEmployee set Gender =@Gender where Id= @EmpId
               end
             If(UPDATE(DeparmentId))
               begin
                 update tblEmployee set DeparmentId =@DepartmentId where Id= @EmpId
               end
             insert into tblAudit values('Employee succefully Update with Id ' + CAST(@EmpId as varchar(5)) + 'and insert into trigger in date' + CAST(Getdate() AS nvarchar(30)))
          End
  END
Now try to Update data from tblEmployee, If we try to update id which is not exists than return message Employee with Id not exits
update tblEmployee set Name= 'janee' where id=5
Instead-of-update-Trigger-show-message
Show Message Employee Not Exit
Now we try to Update id which is already exists return message successfully row effect
update tblEmployee set Name= 'janee' where id=1
Now check data from tables.
Instead-of-update-trigger
Select all tables After, Instead of  Update Trigger fire


Example 2

For more understand about INSTEAD OF UPDATE Trigger we take another trigger example.

First we create another table that hold all activity of main table done by user.

create table tblAuditDetailsBy
(
  Id int not null Primary key identity(1,1),
  EmpId int Not Null,
  EmpOldName varchar(30) Not Null,
  EmpNewName varchar(30) Not Null,
  EmpOldGender char(8) Not Null,
  EmpNewGender char(8) Not Null,
  EmpOldDeparmentId int Not Null,
  EmpNewDeparmentId int Not Null,
  AuditAction varchar(1000) Not Null,
  ActionTakenBy varchar(50) Not Null,
  AuditTime datetime not null default Getdate(),
  ServerName varchar(100) Not Null,
  ServerInstanceName varchar(100) Not Null
)
Now create the INSTEAD OF UPDATE Trigger for “tblEmployee”
create trigger trtblEmployeeInsteadOfDeleteByDetail
ON tblEmployee
INSTEAD OF UPDATE
As
 BEGIN
     Declare @EmpId int, 
             @OldEmpName varchar(30), @NewEmpName varchar(30),            
             @OldEmpGender varchar(8), @NewEmpGender varchar (8),
             @OldEmpDepatmentId int, @NewEmpDepatmentId int,
             @EmpMessage varchar(300),@AuditAction varchar(2000),
             @ActionTakenBy varchar(100),@AuditTime varchar(50),
             @ServerName varchar(100), @ServerInstanceName Varchar(100);
     select  @EmpId=D.Id,             --Id Not Change
             @OldEmpName = D.Name, 
             @OldEmpGender = D.Gender,
             @OldEmpDepatmentId = D.DeparmentId from deleted D;
     select  @NewEmpName = I.Name, --delete not only keep id column value, keep all column value for which id we want delete. 
             @NewEmpGender= I.Gender, @NewEmpDepatmentId= I.DeparmentId
             from inserted I
      
     If not exists(Select Id from tblEmployee where Id = @EmpId)   --If Id not Exists in Cloumn than through message, you can check other condition like departmentId =1 or Gender=Male, than you can print message you can not delete
       Begin
           SET @EmpMessage  = 'Employee With Id ' + CAST(@EmpId as varchar(5)) + 'Not Exists in the DataBase.'
           Raiserror(@EmpMessage, 16, 1)
           Print 'INSTEAD OF Update Triggers in SQL Server not fire because Employee Not Exists' 
           RollBack
       End
       Else
          Begin
             SET @AuditAction='Update Record '
             If(@OldEmpName <> @NewEmpName)
               begin
                  set @AuditAction = @AuditAction + 'Name from ' + @OldEmpName + 'to ' + @NewEmpName + ', '
                  update tblEmployee set Name= @NewEmpName where id=@EmpId
               end
             If(@OldEmpGender <> @NewEmpGender)
               begin
                 set @AuditAction =@AuditAction + 'Gender from ' + @OldEmpGender + 'to ' + @NewEmpGender + ', '
                 update tblEmployee set Gender= @NewEmpGender where id=@EmpId
               end
             If(@OldEmpDepatmentId <> @NewEmpDepatmentId)
               begin
                 set @AuditAction =@AuditAction + 'DeaparmentId from ' + CAST(@OldEmpDepatmentId as varchar(10)) + 'to ' + CAST(@NewEmpDepatmentId As varchar(10))+ ', '
                 update tblEmployee set DeparmentId= @NewEmpDepatmentId where id=@EmpId
               end
    set @ActionTakenBy = SYSTEM_USER;
 set @ServerName = CAST( SERVERPROPERTY('ServerName') AS VARCHAR(50));          -- select @@SERVERNAME return server name
 set @ServerInstanceName = CAST( SERVERPROPERTY('MachineName') AS VARCHAR(50));    --SELECT @@servicename return current machine name
             
            insert into tblAuditDetailsBy (EmpId, EmpOldName, EmpNewName, EmpOldGender, EmpNewGender,
                                 EmpOldDeparmentId, EmpNewDeparmentId, AuditAction,
                                ActionTakenBy, AuditTime,ServerName,ServerInstanceName)
                         values(@EmpId,@OldEmpName, @NewEmpName, @OldEmpGender, @NewEmpGender,
                                @OldEmpDepatmentId, @NewEmpDepatmentId, @AuditAction,
                                @ActionTakenBy,GETDATE(), @ServerName, @ServerInstanceName)
             PRINT 'Successfully Delete Data with ID= ' + CAST(@EmpId as varchar(5)) + CAST(Getdate() AS nvarchar(30));
             PRINT 'Fired the INSTEAD OF Update Triggers in SQL Server'
          End
 END
Now try to Update data from tblEmployee, If we try to Update id which is not exists than return message Employee with Id not exits
update tblEmployee set Name= 'jhone', Gender='Male' where id=5
But If we try to Update id which is already exists return message successfully row effect
update tblEmployee set Name= 'jhone', Gender='Male' where id=1
Instead-of-update-trigger
Update Tables

Now check data from tables.
select all-tables-for-Instead-of-update-tables




Response.Redirect in ASP.NET and use of EndResponse


Response.Redirect in ASP.NET


In the previous part we study about what is page navigation and there types and also study HyperLink type page navigation technique in detail. In this part we will study about Response.Redirect which also one of the navigation techniques in ASP.NET which is use to move from one web form to another that means use to redirect a user to another URL.

According to MSDN website it redirect to new URL whether execution of the current page terminated.

Redirect is a method of the HttpResponse class in ASP.NET applications, when hover mouse on it Response class and return type is void.

The HttpResponse class has two overloaded method of versions of the Redirect.

The first method takes one input parameter as a URL of the other page.
e.g.  Response.Redirect("~/default.aspx");

response.redirect c# true false


Another one is take two parameters, one as a URL and second is a Boolean value (true or false).
Response.Redirect("~/default.aspx",false);    // means current page execution is not terminated and code written after the Response.Redirect("default.aspx", false) is executed and then after the page is redirected to the default.aspx.
or
Response.Redirect("~/default.aspx",true); 
When we try to use Response.Redirect("default.aspx", false) in a page then the execution of current page is not terminated instead of this code written after the Response.Redirect is executed and then after that page is redirected to the given page.

When we try to use Response.Redirect("default.aspx",true) which is by default true then the execution of current page is terminated and code written after the Response.Redirect is not executed instead of executing code written after the Response.Redirect ,the page is redirected to the given page.

Note:-

1. When you use the first overloaded version in the code, the second overloaded version is called automatically and endResponse passed True .

2. When we pass false as second parameter value that indicates we do not want an exception to be thrown to terminate the page. 3. When we use overloaded method, URL (string type) is mandatory parameter and endResponse (Boolean type, by default true) is optional parameter.

4. URL is the string parameter which takes the url or page name and endResponse is the boolean parameter which has true and false values.

We create z-test.aspx page in ASP.NET and drag and drop buttons control in this page from toolbox.
<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="z-test.aspx.cs" Inherits="AspDotNets.z_test" %>
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title></title>
</head>
<body>
    <form id="form1" runat="server">
<asp:Button ID="button1" runat="server" Text="Button 1" OnClick="button1_Click" /><br />
<asp:Button ID="button2" runat="server" Text="Button 2" OnClick="button2_Click"/><br /> 
 <asp:Button ID="button3" runat="server" Text="Button 3" OnClick="button3_Click" /><br />
<asp:Button ID="button4" runat="server" Text="Button 4" OnClick="button4_Click" /><br />
</form>
</body>
</html>
Now write the code in code behind (z_test.aspx.cs).
using System;
namespace AspDotNets
{
    public partial class z_test : System.Web.UI.Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            
        }
        protected void button1_Click(object sender, EventArgs e)
        {
            Response.Redirect("~/test2.aspx");
        }
        protected void button2_Click(object sender, EventArgs e)
        {
            Session["Before_redirect"] = "This String is Before Response.Redirect When EndResponse values is false"; 
            Response.Redirect("~/z-test2.aspx",false);
            Session["After_redirect"] = "This String is after Response.Redirect When EndResponse values is false"; 

        }
        protected void button3_Click(object sender, EventArgs e)
        {
            Session["Before_redirect"] = "This String is Before Response.Redirect When EndResponse values is true"; 
            Response.Redirect("~/z-test2.aspx",true);
            Session["After_redirect"] = "This String is after Response.Redirect When EndResponse values is true"; 
        }
        protected void button4_Click(object sender, EventArgs e)
        {
            Response.Redirect("http://web-designing-developing-tutorials.blogspot.in/");
        }

    }
}
Now create a webform (z-test2.aspx) and write the code in code behind (z_test2.aspx.cs).
using System;
namespace AspDotNets
{
    public partial class z_test2 : System.Web.UI.Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            Response.Write("String receive from session variable Before_redirect =" + Session["Before_redirect"] + ""); 
            Response.Write("String receive from session variable After_redirect =" + Session["After_redirect"]);        
        }
     }
}
When click on Button 1

When click button1 than simply transfer to page z-test2.aspx. In button 1 we does not transfer any value to z-test.aspx.cs because we does not use session variable in button1.

But if click first button 2, or 3 than click one than session store string in session variable because Session variable store by default 20 min. In detail we study later part.

When click on Button 2

String store in session variables “Before_redirect” and “After_redirect” just before and after Response.Redirect, these session variables strings will be accessed on another page (we name it z-test2.aspx).

If we try to access these session on the other page both before and after session will be accessed because execution of current page is not terminated when EndResponse values is false. i.e code after Response.Redirect will be accessed.


When click on Button 3

Similarly as in button2 string store in session variables “Before_redirect” and “After_redirect” just before and after Response.Redirect, these session variables strings will be accessed on another page.

If we try to access these session on the other page only before Response.Redirect session will be accessed and after session will not be accessed because execution of current page is terminated when EndResponse values is true.


When click on Button 4

When click button4 it move to web-designing-developing-tutorials.blogspot blogger.

Note:-

1. The button 3 rule also apply for button 1 because EndResponse by default true if not use EndResponse.

2. If you use our code to learn than first click on Button1, Button2, than Button3 on order because Session variable store by default 20 min. In detail we study later part.

Understand Response.Redirect flow between client-and-server

When we use response.redirect, there are two request-response cycle round trip will be happend, Suppose, when we click on button immediately postback response is happened for the page and send to web server have code for respose.redirect than web server send response header back to the client and then client initiate new request for the new page and web server receive the request and process and send html page back to the client browser, this type of page navigation technique does not involve two response cycle.

Initial request with redirect                                               
                             ----------------------->

                            Got Response header from server
                           <--------------------------
       Client                                                      Web Server
                              New Request Initiated
                            ------------------------>

                           Response sent back as HTML
                           <-------------------------

NOTE:-

1. Reponse.Redirect is maintained browser history which help to back previous using back button. Redirect can be used to navigate pages/website on the same web server or different web server.

2. Response.Redirect is similar to the HyperLink technique use to navigate any website/Pages on same webserver or different web server.
In the above example, in button4_click event is satisfy this rule. 3. Due to Round trip it is bit slow.

4. After sending headers to the client and try to redirect, you receive an HttpException exception error.

Interview Question:-


Q1. What is difference between Response.Redirect true and Response.Redirect false and Rsponse.Redirect?



previous Related Post