?
Solved

Adding Column that Populates Timestamp upon row insertion SQL Server 2012

Posted on 2013-01-29
5
Medium Priority
?
685 Views
Last Modified: 2013-01-29
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?
0
Comment
Question by:DB-aha
[X]
Welcome to Experts Exchange

Add your voice to the tech community where 5M+ people just like you are talking about what matters.

  • Help others & share knowledge
  • Earn cash & points
  • Learn & ask questions
  • 2
  • 2
5 Comments
 
LVL 7

Expert Comment

by:Ross Turner
ID: 38832991
0
 
LVL 75

Expert Comment

by:Aneesh Retnakaran
ID: 38832995
ALTER TABLE tableName ADD ColumnName datetime2 default sysdatetime()
0
 
LVL 1

Author Comment

by:DB-aha
ID: 38833013
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
 
LVL 75

Accepted Solution

by:
Aneesh Retnakaran earned 2000 total points
ID: 38833022
ALTER TABLE tableName ADD ColumnName datetime2 not null default sysdatetime()
0
 
LVL 1

Author Closing Comment

by:DB-aha
ID: 38833064
This solution had the added NOT NULL that makes life so much easier. Thanks for the resolution.
0

Featured Post

10 Questions to Ask when Buying Backup Software

Choosing the right backup solution for your organization can be a daunting task. To make the selection process easier, ask solution providers these 10 key questions.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

After restoring a Microsoft SQL Server database (.bak) from backup or attaching .mdf file, you may run into "Error '15023' User or role already exists in the current database" when you use the "User Mapping" SQL Management Studio functionality to al…
How to leverage one TLS certificate to encrypt Microsoft SQL traffic and Remote Desktop Services, versus creating multiple tickets for the same server.
Michael from AdRem Software outlines event notifications and Automatic Corrective Actions in network monitoring. Automatic Corrective Actions are scripts, which can automatically run upon discovery of a certain undesirable condition in your network.…
In this video, Percona Solutions Engineer Barrett Chambers discusses some of the basic syntax differences between MySQL and MongoDB. To learn more check out our webinar on MongoDB administration for MySQL DBA: https://www.percona.com/resources/we…

762 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question