posted on Sunday, February 12, 2006 9:47 AM by amachanic

GETDATE in a UDF?

An extremely common question in forums is, "How can I use the GETDATE() function in a UDF?"  Because the GETDATE() function is nondeterministic, it is not allowed in SQL Server 2000 UDFs.

To date, I've always made it a point to answer the question the same way:  "Add a  DATETIME parameter to the UDF and pass it in."  Yes, you can create a view that selects GETDATE() and select from the view in your UDF to work around the restriction, but that really seems like a dirty hack to me.  I'm not sure why, but passing in the date just feels cleaner...

But after answering this question the same way so many times, I was shocked to read a blog post by Louis Davidson in which he points out that the restriction has been lifted in SQL Server 2005.  You can now use GETDATE() within a UDF; no need to either pass it in or create the view. 

Great job spotting that change, Louis!  I never would have thought to look for a modification of that behavior.  This is one of those little tiny annoyances that crops up every once in a while (always at a very bad time), and it's good to know that we no longer have to be concerned with how to work around this issue.


Comments

# Running sums, redux @ Tuesday, February 28, 2006 1:07 AM

Siddhartha Gautama, the Buddha, taught us to understand that the key to enlightenment is following the...

Anonymous

# Running sums, redux @ Thursday, July 13, 2006 12:52 AM

Originally posted here.

Siddhartha Gautama, the Buddha, taught us to understand that the key to
enlightenment...

Anonymous

# Running sums, redux @ Monday, January 08, 2007 2:28 PM

Originally posted here . Siddhartha Gautama, the Buddha, taught us to understand that the key to enlightenment

Anonymous