[Webinar] Streamline your web hosting managementRegister Today

x
  • Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 706
  • Last Modified:

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?
0
DB-aha
Asked:
DB-aha
  • 2
  • 2
1 Solution
 
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
 
Aneesh RetnakaranDatabase AdministratorCommented:
ALTER TABLE tableName ADD ColumnName datetime2 not null default sysdatetime()
0
 
DB-ahaAuthor Commented:
This solution had the added NOT NULL that makes life so much easier. Thanks for the resolution.
0

Featured Post

[Webinar] Kill tickets & tabs using PowerShell

Are you tired of cycling through the same browser tabs everyday to close the same repetitive tickets? In this webinar JumpCloud will show how you can leverage RESTful APIs to build your own PowerShell modules to kill tickets & tabs using the PowerShell command Invoke-RestMethod.

  • 2
  • 2
Tackle projects and never again get stuck behind a technical roadblock.
Join Now