Created
June 21, 2017 18:54
-
-
Save yaplex/b479e5645e5d824839fcaee57c2abbf8 to your computer and use it in GitHub Desktop.
This file contains hidden or 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
USE [DatabaseName] | |
create table #AuditRequired([TableName] nvarchar(50), [PKName] nvarchar(50)) | |
insert into #AuditRequired values ('User', 'UserId') | |
insert into #AuditRequired values ('Role', 'RoleId') | |
insert into #AuditRequired values ('Promotion', 'PromotionId') | |
Declare @tableName nvarchar(50) = '' | |
Declare @primaryKeyName nvarchar(50) = '' | |
While (Select Count(*) From #AuditRequired) > 0 | |
Begin | |
Select Top 1 @tableName = TableName, @primaryKeyName = PKName From #AuditRequired | |
----------------------------------------------------- | |
-- adding new audit columns to the table and creating trigger to update them | |
exec ('ALTER TABLE [dbo].[' + @tableName + '] ADD ModifyDt datetime NULL, ModifyBy nvarchar(50) NULL') | |
exec ('ALTER TABLE [dbo].[' + @tableName + '] ADD CONSTRAINT DF_' + @tableName + '_ModifyDt DEFAULT GETUTCDATE() FOR ModifyDt') | |
exec ('ALTER TABLE [dbo].[' + @tableName + '] ADD CONSTRAINT DF_' + @tableName + '_ModifyBy DEFAULT CURRENT_USER FOR ModifyBy') | |
exec ('ALTER TABLE [dbo].[' + @tableName + '] SET (LOCK_ESCALATION = TABLE)') | |
exec(' | |
CREATE TRIGGER [dbo].onRowUpdate_' + @tableName + ' ON [dbo].[' + @tableName +'] AFTER UPDATE | |
AS | |
BEGIN | |
SET NOCOUNT ON; | |
UPDATE t SET ModifyDt = getutcdate(), ModifyBy = CURRENT_USER | |
FROM [dbo].[' + @tableName + '] AS t | |
WHERE EXISTS (SELECT 1 FROM inserted WHERE ' + @primaryKeyName + ' = t.'+ @primaryKeyName + ' ); | |
END | |
') | |
----------------------------------------------------- | |
Delete #AuditRequired Where TableName = @tableName and PKName = @primaryKeyName | |
End | |
drop table #AuditRequired |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment