Adding Column that Populates Timestamp upon row insertion SQL Server 2012

Hello all,

I have several tables in SQL Server 2012 that I would like to add a column to each that will populate with the record creation date and time when I write new records to the table. How can this be done?
LVL 1
DB-ahaAsked:
Who is Participating?
 
Aneesh RetnakaranConnect With a Mentor Database AdministratorCommented:
ALTER TABLE tableName ADD ColumnName datetime2 not null default sysdatetime()
0
 
Ross TurnerManagement Information Support AnalystCommented:
0
 
Aneesh RetnakaranDatabase AdministratorCommented:
ALTER TABLE tableName ADD ColumnName datetime2 default sysdatetime()
0
 
DB-ahaAuthor Commented:
I found one way that requires me to rebuild the tables. As of now this is ok because there is no data in the tables, but I would need to know another way that would allow for this change when data is present. Thanks

CREATE TABLE Example
(
SomeField INTEGER,
DateCreated DATETIME NOT NULL DEFAULT(GETDATE())
)
0
 
DB-ahaAuthor Commented:
This solution had the added NOT NULL that makes life so much easier. Thanks for the resolution.
0
Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.

All Courses

From novice to tech pro — start learning today.