The reason why your dynamic sql doesn't work is because the inserted table is out of scope. And I have to say that this audit table would be very hard to make use of. It would be far better to just copy the entire old row to an audit table that has the same structure as the real table. I takes a little more storage but it's A LOT easier to work with. here's the code I use for my audit tables...absolutely free
:CREATE TABLE [dbo].[MyTable] ( [RegId] [bigint] NOT NULL, [RegTime] [datetime] NOT NULL, [ReferenceNo] [char](50) NOT NULL, [RecordType] [smallint] NOT NULL, [DataVersion] [smallint] NOT NULL, [ModifiedDate] [datetime] NOT NULL, [ModifiedBy] [varchar](200) NOT NULL,)GOCREATE TABLE [dbo].[MyTable_audit]( [RegId] [bigint] NOT NULL, [RegTime] [datetime] NOT NULL, [ReferenceNo] [char](50) NOT NULL, [RecordType] [smallint] NOT NULL, [DataVersion] [smallint] NOT NULL, [ModifiedDate] [datetime] NULL, [ModifiedBy] [varchar](200) NULL, [IsDeleted] [tinyint] NULL,)GOCREATE TRIGGER [dbo].[AuditDel] ON [dbo].[MyTable]FOR DELETEAS SET NOCOUNT ONINSERT INTO MyTable_audit ([RegId],[RegTime],[ReferenceNo],[RecordType],[DataVersion],[ModifiedDate],[ModifiedBy],[IsDeleted]) SELECT del.[RegId], del.[RegTime], del.[ReferenceNo], del.[RecordType], del.[DataVersion], del.[ModifiedDate], del.[ModifiedBy], [IsDeleted] = 1FROM deleted delGOCREATE TRIGGER [dbo].[AuditUpd] ON [dbo].[MyTable]FOR UPDATE AS SET NOCOUNT ONUPDATE reg SET reg.DataVersion = ins.DataVersion + 1, reg.ModifiedDate = GETDATE(), reg.ModifiedBy = SYSTEM_USERFROM MyTable reg INNER JOIN inserted ins ON reg.RegId = ins.RegIdINSERT INTO MyTable_audit ([RegId],[RegTime],[ReferenceNo],[RecordType],[DataVersion],[ModifiedDate],[ModifiedBy],[IsDeleted]) SELECT del.[RegId], del.[RegTime], del.[ReferenceNo], del.[RecordType], del.[DataVersion], del.[ModifiedDate], del.[ModifiedBy], [IsDeleted] = 0FROM deleted delGO
- LumbagoIf the facts don't fit the theory, change the facts. Albert Einstein