Last active
August 23, 2021 13:38
-
-
Save fbehrens/41b6f0780ca8c49aa445c05e6dbc2ea0 to your computer and use it in GitHub Desktop.
tsql autid trigger.sql
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
/* | |
DROP TABLE GUESTS | |
go | |
CREATE TABLE GUESTS ( | |
ID int IDENTITY(1,1) PRIMARY KEY, | |
NAME VARCHAR(50), | |
SURNAME VARCHAR(50), | |
) | |
DROP TABLE Audit | |
GO | |
CREATE TABLE Audit( | |
ID int | |
, FieldName VARCHAR(128) | |
, Old VARCHAR(1000) | |
, modified_at datetime | |
) | |
insert into guests (name) values ('Frank') | |
select id,name from guests | |
delete from audit | |
select * from Audit | |
*/ | |
ALTER TRIGGER TR_GUESTS_AUDIT ON GUESTS FOR UPDATE AS | |
DECLARE @now DATETIME | |
select @now = GETDATE() | |
insert | |
into audit | |
(id,fieldname,old,modified_at) | |
select i.id,'name',d.name,@now | |
from inserted i | |
join deleted d on i.id = d.id | |
where isnull(i.name,'[NULL]') <> isNull(d.name,'[NULL]') | |
delete from audit | |
select * from guests where id = 1 | |
update guests set name = 'Frank' where id =1 | |
update guests set name = NULL where id =1 | |
update guests set name = 'Horst' where id =1 | |
select * from audit | |
GO | |
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
select top 10 * from users_workplace | |
-- CREATE TABLE Audit( | |
-- ID int | |
-- , FieldName VARCHAR(128) | |
-- , Old VARCHAR(1000) | |
-- , modified_at datetime | |
-- ) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment