Hello and thank you in advance for any help! I've got to create an
audit trail of all changes to a database. After perusing this group
and the books I've got, it looks like a set of archive tables &
triggers are the way to go. But I've never written any triggers and
I'm pretty marginal on Transact-SQL. Below are my tables & the
triggers I've just written; the syntax checks but I'm still not sure I
know what I'm doing.
I want to copy the entire row into an archive table after any insert
or update to the original table. I've got no PKs/ FKs/ indices/
constraints on the archive table; column datatypes and lengths match
between tables. (I know it will get huge, but I'll deal with that.)
There won't be any deletes to worry about for now, and only one row
will be updated at a time (manual data entry from a web front end).
I've added a timestamp column to the archive table, and I'd like to
include an "action taken" as part of the archive.
Will these triggers do what I need?
CREATE TABLE [dbo].[tbl_Base1] (
[Base1ID] [smallint] IDENTITY (1, 1) NOT NULL ,
[Base1Type] [varchar] (25) NOT NULL ,
[Base1ItemDescr] [varchar] (50) NOT NULL ,
[Base1Group] [varchar] (25) NULL ,
[Status] [bit] NOT NULL ,
[UserID] [varchar] (10) NOT NULL ,
[DeptID] [smallint] NOT NULL ,
[UpdateDt] [datetime] NOT NULL ,
[UpdateBy] [varchar] (100) NOT NULL ,
) ON [PRIMARY]
GO
CREATE TABLE [dbo].[arch_tbl_Base1] (
[Base1ID] [smallint] NOT NULL ,
[Base1Type] [varchar] (25) NOT NULL ,
[Base1ItemDescr] [varchar] (50) NOT NULL ,
[Base1Group] [varchar] (25) NULL ,
[Status] [bit] NOT NULL ,
[UserID] [varchar] (10) NOT NULL ,
[DeptID] [smallint] NOT NULL ,
[UpdateDt] [datetime] NOT NULL ,
[UpdateBy] [varchar] (100) NOT NULL ,
[ActionTaken] [varchar] (15) NOT NULL ,
[TxnSeq] [timestamp] NOT NULL
) ON [PRIMARY]
GO
CREATE TRIGGER trgInsert_tblBase1 ON [dbo].[tbl_Base1]
FOR INSERT
AS
INSERT INTO arch_tbl_Base1 (Base1ID, Base1Type, Base1ItemDescr,
Base1Group, Status, UserID, DeptID, UpdateDt, UpdateBy, ActionTaken)
SELECT Base1ID, Base1Type, Base1ItemDescr, Base1Group, Status, UserID,
DeptID, UpdateDt, UpdateBy, 'Insert' AS ActionTaken
FROM INSERTED
CREATE TRIGGER trgUpdate_tblBase1 ON [dbo].[tbl_Base1]
FOR UPDATE
AS
INSERT INTO arch_tbl_Base1 (Base1ID, Base1Type, Base1ItemDescr,
Base1Group, Status, UserID, DeptID, UpdateDt, UpdateBy, ActionTaken)
SELECT Base1ID, Base1Type, Base1ItemDescr, Base1Group, Status, UserID,
DeptID, UpdateDt, UpdateBy, 'Update' AS ActionTaken
FROM UPDATED
Thanks again!
jamileh