Create a trigger that inserts values into a new table when a column is updated
This is for all changes and all columns, but you can modify how you like:
USE [DB]
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE TRIGGER [dbo].[trMyTrigger]
ON [dbo].[MyTable]
AFTER INSERT, UPDATE, DELETE
NOT FOR REPLICATION
AS
-- SET NOCOUNT ON added to prevent extra result sets from
-- interfering with caller queries select statements.
-- if an update/insert/delete occurs on the main table, the number of records affected
-- should only be based on that table and not what records the triggers may/may not
-- select.
SET NOCOUNT ON;
-- Determine if this is an insert,update, or delete action
DECLARE @action AS CHAR(1)
DECLARE @count AS INT
SET @action = 'I' -- SET action to 'I'NSERT by default.
SELECT @count = count(*) FROM DELETED
IF @count > 0
BEGIN
SET @action= 'D' -- SET action to 'D'ELETED.
SELECT @count = count(*) FROM INSERTED
IF @count > 0
SET @action = 'U' -- SET action to 'U'PDATED.
END
IF @action = 'D'
-- THIS IS A DELETE RECORD ACTION
BEGIN
INSERT INTO myBackupTable
SELECT *,GETDATE() AS changeDate, 'DELETE' AS task FROM DELETED
END
ELSE
BEGIN
IF @action = 'I'
-- this is an INSERT record action
BEGIN
INSERT INTO myBackupTable
SELECT *,GETDATE() AS changeDate, 'INSERT' as task FROM INSERTED
END
ELSE
-- this is an UPDATE record action
BEGIN
INSERT INTO myBackupTable
SELECT *,GETDATE() AS changeDate, 'UPDATE' as task FROM INSERTED
END
END
Something like this should do what you need. You would have the INSERT
statements below insert values indicating the operation performed into MyLogTable
.
CREATE TRIGGER [dbo].[TRIG_MyTable]
ON [dbo].[MyTable]
AFTER INSERT, UPDATE
AS
DECLARE @INS int, @DEL int
SELECT @INS = COUNT(*) FROM INSERTED
SELECT @DEL = COUNT(*) FROM DELETED
IF @INS > 0 AND @DEL > 0
BEGIN
-- a record got updated, so log accordingly.
INSERT INTO MyLogTable
SELECT 'New Values', getdate() FROM INSERTED
INSERT INTO MyLogTable
SELECT 'Old Values', getdate() FROM DELETED
END
ELSE
BEGIN
-- a new record was inserted.
INSERT INTO MyLogTable
SELECT 'Insert', getdate() FROM INSERTED
END
If you wanted to you could also add columns from INSERTED
and DELETED
to your log table as well if you wanted to capture the actual column values that got inserted or updated.
create trigger trigge on abs
instead of update as
declare @idd int , @pricee money
select @idd= ProductID from inserted
select @pricee = ListPrice from inserted
insert into prod values ( @idd , @pricee)
print ' cannot change'