Last active
August 29, 2015 14:01
-
-
Save dougludlow/d5432a58875f7c01197b to your computer and use it in GitHub Desktop.
Audit log triggers on select tables
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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