Skip to content

Instantly share code, notes, and snippets.

@dougludlow
Last active August 29, 2015 14:01
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save dougludlow/d5432a58875f7c01197b to your computer and use it in GitHub Desktop.
Save dougludlow/d5432a58875f7c01197b to your computer and use it in GitHub Desktop.
Audit log triggers on select tables
SET NOCOUNT ON
DECLARE
@table sysname,
@sql varchar(2000)
SELECT * INTO #tables FROM INFORMATION_SCHEMA.Tables WHERE TABLE_NAME IN ('Post', 'PostArea', 'Comment', 'Location', 'Attachment')
SELECT @table = MIN(TABLE_NAME) FROM #tables
WHILE @table IS NOT NULL
BEGIN
SELECT @sql = N'
CREATE TRIGGER [dbo].[Audit_' + @table + '_TR]
ON [dbo].[' + @table + ']
AFTER UPDATE
AS
BEGIN
SET NOCOUNT ON
DECLARE @command NVARCHAR(1000)
DECLARE @old XML
DECLARE @userId VARCHAR(255)
DECLARE @date DATETIME
DECLARE @action AS CHAR(1)
SET @action = ''U''
SET @userId = (SELECT TOP 1 LastModifiedUserId FROM INSERTED)
SET @date = GETDATE() --(SELECT TOP 1 LastModifiedDate FROM INSERTED)
SELECT @old = (SELECT * FROM DELETED FOR XML PATH(''' + @table + '''))
INSERT INTO [dbo].[Audit] ([UserId], [Date], [Action], [Entity], [PreviousValue])
SELECT
[UserId] = @userId,
[Date] = @date,
[Action] = @action,
[Entity] = ''' + @table + ''',
[PreviousValue] = @old
END
'
EXEC(@sql)
SELECT @table = MIN(TABLE_NAME) FROM #tables WHERE TABLE_NAME > @table
END
DROP TABLE #tables
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment