Introduction
In this article I have explained how to insert the records in one table and after using an insert trigger on the table, the records are automatically stored in another table. You can see the After Update Trigger in my next article.
Trigger
Triggers are database objects that are automatically executed when DDL or a DML command statement is executed. Triggers are used to evaluate the data before or after data modification using DDL/DML statements. Triggers are an action performed implicitly.
Why we use Triggers?
- Provide auditing
- Prevent invalid transactions
- Maintain Synchronous table replicates
- Modify table data when DML statements are issued against views
- Automatically generate derived column values
After Triggers
"After" triggers are fired by the DML statements and can be defined only on tables, not on views. "After" triggers are executed after an insert, update or delete on a specified table.
- After Insert Trigger
- After Delete Trigger
- After Update Trigger
Create Table-1
Create Database DemoTriggers
use DemoTriggers
Create table Table1
(
CustID int primary key,
CustName varchar(max),
CustAddress nvarchar(max),
PaidAmmount decimal
)
Create Table-2
Create table Table2
(
CustID int primary key,
CustName varchar(max),
CustAddress nvarchar(max),
PaidAmmount decimal
)
Create Procedure for Insertion
create proc InsertData
@cid int,
@cname varchar(max),
@cadd nvarchar(max),
@pammount decimal
as
begin
insert into Table1 values(@cid,@cname,@cadd,@pammount)
end
Create Trigger For Insert
create trigger insertMyTRIGGER on Table1
after insert
as
declare @cid int;
declare @cname varchar(max);
declare @cadd nvarchar(max);
declare @pammount decimal;
select @cid=i.CustID from inserted i;
select @cname=i.CustName from inserted i;
select @cadd=i.CustAddress from inserted i;
select @pammount=i.PaidAmmount from inserted i;
insert into Table2 values(@cid,@cname,@cadd,@pammount)
The create trigger statement creates a trigger and an "on" clause specifies the table name on which the trigger is to be attached. In the trigger body the table named "inserted" has been used. It is a logical table and contains the row that has been inserted.
Now I want to show the effect of an "after insert" trigger in the database; just use the following procedure.
Step 1:
Open Visual Studio then seelct "Create New Project" --> "F# Console Application".

Step 2:
Now go the Solution Explorer on to the right side of the application. Select the references and right-click on it and select "Add references".


Step 3:
After selecting "Add References", in the framwork template you need to select "System.Windows.Forms", "System.Drawing", "System.Xml" and "System.Data" while holding down the Ctrl key and click on "Ok".

Step 4:
Write the following code in the F# editor:






Comments
Join the conversation! Your thoughts help the community grow.