Solved

Adding Column that Populates Timestamp upon row insertion SQL Server 2012

Posted on 2013-01-29
5
650 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

Zoho SalesIQ

Hassle-free live chat software re-imagined for business growth. 2 users, always free.

Question has a verified solution.

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

Suggested Solutions

Title # Comments Views Activity
How much extra disk space I need for sql backup? 7 76
Row-Level Security 2 32
T SQL Update Table from another table 5 42
TSQL previous 5 22
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…
This is a video describing the growing solar energy use in Utah. This is a topic that greatly interests me and so I decided to produce a video about it.
The Email Laundry PDF encryption service allows companies to send confidential encrypted  emails to anybody. The PDF document can also contain attachments that are embedded in the encrypted PDF. The password is randomly generated by The Email Laundr…

932 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

14 Experts available now in Live!

Get 1:1 Help Now