Skip to content

Instantly share code, notes, and snippets.

@realdubb
Forked from bdcravens/add-timestamps.sql
Created March 16, 2018 16:40
Show Gist options
  • Save realdubb/f9a20b584c19f8d9c55ca9020cce134c to your computer and use it in GitHub Desktop.
Save realdubb/f9a20b584c19f8d9c55ca9020cce134c to your computer and use it in GitHub Desktop.
SQL Server - add createdAt and updatedAt columns, automatically updates
ALTER TABLE myTable
add createdAt datetime
CONSTRAINT DF_myTable_createdat DEFAULT GETDATE()
ALTER TABLE myTable
add updatedAt datetime
CONSTRAINT DF_myTable_updatedAt DEFAULT GETDATE()
go
create trigger trg_myTable_update on myTable for update as
begin
update myTable
set updatedAt = getDate()
from myTable inner join deleted d
on myTable.id=d.id
end
go
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment