This thread has been interesting to see some solutions for a relatively simple problem. When writing code I always keep one eye on performance, and as a general rule functions are detrimental to performance.
With this in mind I set about testing each of the solutions given by:
-
creating each as a UDF
-
creating a table with all the years from 17753 to 9999
-
running each function over the table 20 times and summing the time taken in milliseconds
The UFD's with fewer function call should be faster than those with more. And the results I got on my meagre PC box were:
-
tosc (0 functions) time: 4531 milliseconds
-
rajan (0 functions) time: 4739
-
vedmondson (0 functions) time: 4864
-
khodges (2 functions) time: 5905
-
johnrogerson (3 functions) time: 92584
-
aprato (4 functions) time: 92665
There was a clear correlation between number of functions and time taken, with tosc's solution the fastest of the 0-function group. However, if we drop the UDF then khodges solution is the simplest to use in-line, ie: "isdate('29 Feb ' + cast(TheYear AS char(4)))" or "isdate('29 Feb ' + TheCYear)" if TheYear is already char (1 function less) and we get:
-
isdate('29 Feb ' + TheCYear) time: 2195
-
isdate('29 Feb ' + cast(TheYear AS char(4))) time: 2589
I do agree that it's better to use SQL Server's grunt, but not if it takes all day. If using a UDF then rolling your own seems to be the best idea, though using isdate() - even with the cast() - is simple enough that having a UDF seems irrelevant.
Anyway, just my 2 cents. :)
S.