Solved

Adding Column that Populates Timestamp upon row insertion SQL Server 2012

Posted on 2013-01-29
5
649 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
  • 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 500 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

Threat Intelligence Starter Resources

Integrating threat intelligence can be challenging, and not all companies are ready. These resources can help you build awareness and prepare for defense.

Join & Write a Comment

There have been several questions about Large Transaction Log Files in SQL Server 2008, and how to get rid of them when disk space has become critical. This article will explain how to disable full recovery and implement simple recovery that carries…
Occasionally there is a need to clean table columns, especially if you have inherited legacy data. There are obviously many ways to accomplish that, including elaborate UPDATE queries with anywhere from one to numerous REPLACE functions (even within…
Sending a Secure fax is easy with eFax Corporate (http://www.enterprise.efax.com). First, Just open a new email message.  In the To field, type your recipient's fax number @efaxsend.com. You can even send a secure international fax — just include t…
In this tutorial you'll learn about bandwidth monitoring with flows and packet sniffing with our network monitoring solution PRTG Network Monitor (https://www.paessler.com/prtg). If you're interested in additional methods for monitoring bandwidt…

757 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

Need Help in Real-Time?

Connect with top rated Experts

19 Experts available now in Live!

Get 1:1 Help Now