I would like to write this as a user defined function:
private double Score(Story s){ DateTime now = DateTime.Now; TimeSpan elapsed = now.Subtract(s.PostedOn); double daysAgo = elapsed.TotalDays; return s.Votes.Count + s.Comments.Count - daysAgo; }
Is this possible to do with a UDF?
You can, but if you’re using SQL Server 2000, you’ll have to pass in the value of ‘now’–UDFs can’t generate any non-deterministic values themselves in SQL Server 2000.
This untested stab at it might be close:
Example usage:
Notes:
The datediff is performed in hours (not days) because the integer result gives you a little more precision when you use finer units.
I passed in all the values because I’ve found lookups within functions to be a really, really bad thing for performance.
When referenced in SQL, don’t forget the
dbo.in front of the function name.If you’re using SQL Server 2005, you can remove the @Now variable and use GETDATE() inline, instead.