This question is just for my personal future knowledge since the database it applies to is already going in a specific direction.
In a SQL Server 2005 database we have a function that returns a DateTime value based on Utc time and the local client’s time zone. This function has been applied in two ways:
- As a function call in the default value for the column
- As a function call within an INSERT statement in various stored procs.
Obviously the first method is easier to implement up front and, arguably, much more scalable in terms of development effort.
My question is whether or not there is a notable advantage in efficiency to using one method over the other in terms of workload on the server/time to complete the transaction. I hope this question isn’t too vague. Thanks for any insights in advance.
If it is the default value, it will be calculated exactly once. If it is part of the stored proc to do inserts it will be calculated only once. If the calculation is done on a proc that does a select (I know you aren’t suggesting this but some future reader might be thinking about it), it would be re-calculated many times.
If it is the default, then you can be sure it will always be populated no matter how the data is entered in the database. If you have something that needs to be updated if the other data changes, then a trigger would keep it up to date no matter how the data got changed. If multiple stored procs might get written to do the same thing (which mught be called by differnt apps), then you are more at risk that different methods to populate the field will be used. Further you are at risk that data will be entered outside the insert proc from the query window, a script, an import, etc. This is especially true if you might need to port large amounts of data from another system or a new client and running one record at a time through an insert proc is too slow.
I say the default function (and a trigger if you need to keep the date updated for any reason) is the easiest to maintain and the way that is least likley to negatively affect data integrity. It is also likely as fast as a stored proc to do the insert and far better than a stored proc that would do the calculation on select instead of on insert.