Can't Get Enough RSS 2.0
 Sunday, December 16, 2007

Sometimes you need to add a CreatedDateTime and ModifiedDateTime columns to your table, here is an easy way to do it...

First create a test table:

Create Table Table_1

(

ID Int Primary Key Identity(1, 1),

Col1 Varchar(50),

CreatedDateTime DateTime Not Null Default Current_Timestamp,

ModifiedDateTime DateTime Null Default Null

)

 

Note that the default value for the column CreatedDateTime is Current_Timestamp.

To update the ModifiedDateTime column we need this trigger:

Create Trigger Table_1_Update On Table_1 After Update

As

Update Table_1 Set ModifiedDateTime = GetDate()

From Table_1 Inner Join Inserted

On Table_1.ID = Inserted.ID

 

Now Test:

Insert Into Table_1 (Col1) Values ('Hello');

Select * From Table_1;

Update Table_1 Set Col1 = 'Hi' Where ID = 1;

Select * From Table_1;

 

ID          Col1                CreatedDateTime         ModifiedDateTime

----------- ------------------- ----------------------- -----------------------

1           Hello               2007-12-16 22:18:39.013 NULL

 

ID          Col1                CreatedDateTime         ModifiedDateTime

----------- ------------------- ----------------------- -----------------------

1           Hi                  2007-12-16 22:18:39.013 2007-12-16 22:18:39.013

Sunday, December 16, 2007 7:22:07 PM UTC  #    Comments [0] -
SQL Server
Name
E-mail
Home page

Comment (Some html is allowed: a@href@title, strike) where the @ means "attribute." For example, you can use <a href="" title=""> or <blockquote cite="Scott">.  

Enter the code shown (prevents robots):

Live Comment Preview
Navigation
Categories
Archive
<December 2007>
SunMonTueWedThuFriSat
2526272829301
2345678
9101112131415
16171819202122
23242526272829
303112345
About the author/Disclaimer

Disclaimer
The opinions expressed herein are my own personal opinions and do not represent my employer's view in any way.

© Copyright 2010
Ghazi Sarhan
Sign In
Statistics
Total Posts: 13
This Year: 0
This Month: 0
This Week: 0
Comments: 4
Themes
Pick a theme:
All Content © 2010, Ghazi Sarhan
DasBlog theme 'Business' created by Christoph De Baene (delarou)