4

I want to create a trigger for logging.So i need event names of INSERT,UPDATE or DELETE.i.e : one of these statements is used in query execution my trigger will trig and starts logging.

SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE TRIGGER LogBuses 
 ON  Bus_table 
 AFTER INSERT,DELETE
 AS 
BEGIN
DECLARE @PlateNo nvarchar(50)
IF INSERT//something like that-INSERTING- DELETING
    SELECT @PlateNo=PlateNo from inserted
insert into Logger (EffectedTable,ActionName,EffectDate,EffectedID) 
VALUES ('Bus_table','Insert',SYSDATETIME (),@PlateNo);
ELSE IF DELETE 
    SELECT @PlateNo=PlateNo from deleted
insert into Logger (EffectedTable,ActionName,EffectDate,EffectedID) VALUES ('Bus_table','Insert',SYSDATETIME (),@PlateNo);

END GO

2 Answers 2

10

You use the inserted and deleted tables. It's inserted if just the inserted table is populated, deleted if just the deleted table is populated, and updated if both tables are populated. Use if exists (select 1 from inserted) to test.

if exists (select 1 from inserted) and exists (select 1 from deleted)
--update
else if exists (select 1 from inserted)
--insert
else if exists (select 1 from deleted)
--delete
Sign up to request clarification or add additional context in comments.

Comments

1

Create a stored procedure that logs, and triggers for each event, that call the procedure, passing the needed data.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.