+1 vote
How to write a simple sql trigger ?

can anyone help me out with simple example for the same ?
asked Jun 4, 2016 in Computer Science - IT by techdoubt | 131 views

1 Answer

+1 vote
Selected Ans.

If you have sql management studio installed , create 2 tables for our example.

Below you have database = one

tables :

  1. event_tags : columns = 
    1. event_id ( int)
    2. tag_id (int)
  2. events : columns =
    1. id (int)
    2. info (nvarchar)

Expand the tables , find triggers , right click and add new trigger


Add trigger code as below :

create  TRIGGER AfterInsertTrigger   
on [events]
AS declare @id int,@tag int;


select @id=i.id from inserted i;
select @tag=i.info from inserted i;

insert into event_tags(event_id,tag_id)
values (@id,@tag);


What does the above code perform ?

  • When values are inserted in table events
  • insert command is triggered and values are inserted into table event_tags

Hence there is no need keep on checking if values are being inserted into table events , triggers does them for you and automate the next action

Now insert values into table event and check event_tags ! ..There you go ,you have triggered successfully

answered Jun 4, 2016 by slow_learner
selected Jun 6, 2016 by techdoubt