+1 vote
86 views
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 | 86 views

1 Answer

+1 vote
Best answer

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]
FOR INSERT
AS declare @id int,@tag int;

BEGIN

    
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);

END
GO

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