开发者

Best and easiet way to capture time

开发者 https://www.devze.com 2023-03-25 01:11 出处:网络
How can Icapture the time at which a record was added to the database - effortlessly. I am using this

How can I capture the time at which a record was added to the database - effortlessly. I am using this

开发者_开发技巧create table YourTable
(
  Created datetime default getdate()
)

ANy other alternatives?


I think that's the canonical approach, do you have a problem with it?

Other approaches would be using an insert trigger, which is probably slower and slightly more complex in that the code is in two places. Or you could channel all updates via an SP, which would also update the Created field - again that's slightly more complex and easy to circumvent unless your permissions are set carefully.


Still in the vein of using a default constraint... there are other values you can consider using -- different advantages to each (involving universal time, precision, etc.).

http://msdn.microsoft.com/en-us/library/ms188383.aspx

Also -- consider the size of your data type -- datetime is 8bytes -- you could define the column as smalldatetime and improve that to 4 bytes (or in 2008, just plain old date, which is 3bytes -- though you might actually like knowing the time as well).

Triggers are also an option, but not preferable IMO -- for one thing, they can be rolled-back if any constraints are violated (such as external relationship to a table you just created, forgetting about the trigger -- oops!)


Options:

  1. DEFAULT COLUMN (as you have)
  2. INSERT TRIGGER that updates the column to the current_timestamp

Option #2 is more foolproof as it is always updated with GETDATE(). Using option #1 allows the user to manually override the Created date by specifying it in the INSERT clause.

0

精彩评论

暂无评论...
验证码 换一张
取 消