Solved

Adding Column that Populates Timestamp upon row insertion SQL Server 2012

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

Free Tool: Subnet Calculator

The subnet calculator helps you design networks by taking an IP address and network mask and returning information such as network, broadcast address, and host range.

One of a set of tools we're offering as a way of saying thank you for being a part of the community.

Question has a verified solution.

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

Suggested Solutions

Title # Comments Views Activity
Loop through SQL parameters and insert to temp table? 4 52
ms sql + get number in list out of total 7 44
sql how to count case when 4 29
While in ##Table - Help 4 22
In this article I will describe the Detach & Attach method as one possible migration process and I will add the extra tasks needed for an upgrade when and where is applied so it will cover all.
In this article we will get to know that how can we recover deleted data if it happens accidently. We really can recover deleted rows if we know the time when data is deleted by using the transaction log.
This video shows how to use Hyena, from SystemTools Software, to bulk import 100 user accounts from an external text file. View in 1080p for best video quality.

679 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