Skip to content

Instantly share code, notes, and snippets.

@fbehrens
Last active August 23, 2021 13:38
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 fbehrens/41b6f0780ca8c49aa445c05e6dbc2ea0 to your computer and use it in GitHub Desktop.
Save fbehrens/41b6f0780ca8c49aa445c05e6dbc2ea0 to your computer and use it in GitHub Desktop.
tsql autid trigger.sql
/*
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
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