SQL SERVER – Capturing INSERT Timestamp in Table

A default can insert timestamp values when the caller omits a datetime column. I use a session-local CURRENT_TIMESTAMP example.

Three vessels retain a supplied tag, an older tag and an empty tag loop.

CREATE TABLE #TestTable
 (ID int, MyDateTime datetime NULL DEFAULT CURRENT_TIMESTAMP);
INSERT #TestTable (ID) VALUES (1);
INSERT #TestTable (ID, MyDateTime) VALUES (2,'20000101'),(3,NULL);
SELECT ID, MyDateTime FROM #TestTable ORDER BY ID;
DROP TABLE #TestTable;
Historical insertion-time output for the original DEFAULT example.
Historical insertion-time output for the original DEFAULT example.

Row 1 receives current server-local datetime. Row 2 retains its explicit historical value. Row 3 remains NULL because the column permits it. Defaults apply to omitted columns or DEFAULT, rather than explicitly supplied NULL.

CURRENT_TIMESTAMP returns datetime. SQL Server timestamp instead names the deprecated synonym for rowversion, a binary version marker. For greater precision and UTC, consider datetime2 with SYSUTCDATETIME().

This default does not update itself when a row changes. Define who can insert or modify its value. Assess stronger auditing requirements separately.

Related reading

An insertion-time default is not a tamper-proof audit trail, it is a value supplied under defined insert conditions.

Published by Pinal Dave on SQLAuthority. More of my work at pinaldave.com.


Discover more from SQL Authority with Pinal Dave

Subscribe to get the latest posts sent to your email.

SQL Constraint and Keys, SQL DateTime, SQL Scripts, SQL Server
Previous Post
Custom Query Shortcuts in SSMS: Run Your Own Procedure
Next Post
SQL SERVER – Database Engine TCP Port and Browser UDP Port

Related Posts

1 Comment. Leave new

  • Abdul Fattah
    June 6, 2021 11:51 am

    CREATE TABLE TestTable (ID INT, MyDateTime DATETIME DEFAULT GETDATE())
    GO

    The above should also give the same result, what do you recommend GETDATE function or CURRENT_TIMESTAMP?

    Reply

Leave a Reply

Your email address will not be published. Required fields are marked *

Fill out this field
Fill out this field
Please enter a valid email address.