Yes, this is the path I would take even for auditing issues (of break I would also use a field to identify the user who made the change, but that’s not the case). For SQL Server 2005 you can use a value default GETDATE()
or (CURRENT_TIMESTAMP
) for the date of insertion and a Trigger for the update date. For SQL Server 2008+ you can use the function SYSDATETIME()
and the most precise type DATETIME2
.
CREATE TABLE dbo.MinhaTabela
(
ID INT IDENTITY(1,1) PRIMARY KEY,
-- suas colunas
DataDeInclusao DATETIME NOT NULL
CONSTRAINT DF_MinhaTabela_Inclusao DEFAULT (GETDATE()),
DataDeAtualizacao DATETIME NULL -- Ou com DEFAULT de acordo com seus requisitos
);
CREATE TRIGGER dbo.TRG_MinhaTabelaAtualizada
ON dbo.MinhaTabela
AFTER UPDATE
AS
UPDATE dbo.MinhaTabela
SET DataDeAtualizacao = GETDATE()
FROM Inserted i
WHERE i.ID = dbo.MinhaTabela.ID;
See that to meet your requirement only one column DataUltimaAtualizacao
(with the default Constraint and the Trigger) would be sufficient, but it is always good to differentiate update insertion.
Finally, don’t forget to index the two dates (to optimize your queries).
CREATE INDEX IDX_MinhaTabelaInclusao ON dbo.MinhaTabela(DataDeInclusao);
CREATE INDEX IDX_MinhaTabelaAtualizacao ON dbo.MinhaTabela(DataDeAtualizacao);
Example in SQL Fiddle
Sources: