Skip to content

Instantly share code, notes, and snippets.

@kzelda
Forked from bdcravens/add-timestamps.sql
Created December 24, 2017 09:40
Show Gist options
  • Save kzelda/7b1b669276d518400739c62f00c51159 to your computer and use it in GitHub Desktop.
Save kzelda/7b1b669276d518400739c62f00c51159 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