Click here to Skip to main content
15,881,882 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
I have a c# program that periodically writes update and insert commands to a db. In my sql table i have a column called modifiedDate that is suppose to get the current datetime when the row is inserted into the table. I used a stement like this to set up this column that way.

SQL
ALTER TABLE MyTable
ADD CONSTRAINT DF_MyTable_MyColumn
DEFAULT GETDATE() FOR MyColumn


And this works great when my app sends an insert statement to the db, but i've noticed that when i do an update statement, the modifiedDate field does not update with the current date and time.

I would have thought that since that field was setup to retrieve the date when new data occurred i was not including it at all in my insert statement.

SQL
Update table set name= 'Bob', address = 'Main Street'' where id = '28'


How can I allow this field to getdate() everytime data is inserted or updated?

Thanks in Advance!
Posted
Comments
PIEBALDconsult 7-Jun-13 0:06am    
Or try not to do updates at all.

1 solution

A default constraint only works on inserts, for an update use a trigger. Triggers are the best way, because this logic is intimately associated with the table, and not the application. This is just about the only obvious proper use of a trigger that I can think of, apart from more granular referential integrity.
Please see : Create a Modified On Column in SQL Server[^]

And also check one similar thread : here[^]


--Amit
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900