Monday, April 22, 2013

Insert Trigger with custom message in SQL SERVER 2012

Insert Trigger in SQL SERVER 2012


Create a  Table called Sports

CREATE TABLE [dbo].[Sports] (
    [Id]      INT          IDENTITY (1, 1) NOT NULL primary key,
    [Name]    VARCHAR (20) NOT NULL,
    [Country] NCHAR (2)    NOT NULL,
   
);


Insert Data Into Sports table

insert into sports(name,country) values
('BaseBall','US'),('Hand FoodBall','US')

insert into sports(name,country) values
('cricket','IN'),('Tennis','IN'),('Hockey','IN'),('Football','IN'



IDNameCountry
1 cricket IN
2 Tennis IN
3 Hockey IN
4 Football IN
5 BaseBall US
6 Hand FoodBall US


Creating a Insert Trigger on Table Sports Which Displays Custom message.


create trigger sports_insert
on [dbo].[sports]
 for insert
as
Declare @msg varchar(max);

select  @msg=concat(inserted.id,' ',inserted.name,' ',inserted.country) from inserted


print @msg+' inserted...'+ cast(@@rowcount as varchar(3));


Now insert into  Sports Table

Insert into sports(name,country) values('Cricket','UK');

You will get  Message Shown below.

8 Cricket UK inserted...1

    (1 row(s) affected)


Tags:  Insert trigger in SQL SERVER 2012,Triggers Example,Triggers Tutorial,Trigger Syntax
How to Write custom Message using Triggers.

No comments:

Post a Comment