In keeping with my previous post, I wanted to show you how you could create the NthOfNextMonth function in .NET and then use it in SQL Server. The function, shown here, look amazingly similar to the T-SQL function.
public class CDateFunctions
public static SqlDate NthOfNextMonth(SqlDate OrigDate, SqlByte NthDay)
if (OrigDate.IsNull == true || (Boolean)(NthDay > OrigDate.AddMonths(2).AddDays(-(OrigDate.AddMonths(2).Day)).Day))
return OrigDate.AddMonths(1).AddDays(-(OrigDate.AddMonths(1).Day) + NthDay);
Actually, this is the entire class, to which we could add other static methods that would be usable as UDFs in SQL Server. Notice how this C# method uses the type SqlDate instead of the DateTime type you would normally expect. Since the function will be receiving its data from SQL Server, the type is one of the new SqlTypes. I could have converted it to DateTime to do the work, but why bother when SqlDate has everything I need to do the job just fine.
Now, to use this in SQL Server “Yukon“, you will have to register the assembly and then create the function, referencing the static method in the assembly when doing so.
CREATE ASSEMBLY DateFunctions FROM 'C:\Projects\Yukon\DateFunctions\bin\release\DateFunctions.dll'
CREATE FUNCTION fnxNthOfNextMonth (@OrigDate Date, @NthDay TinyInt)
EXTERNAL NAME DateFunctions:[Wintellect.SQLServer.CDateFunctions]::NthOfNextMonth
You are now ready to use the UDF. The best part is, it's just a UDF, so you use it like the others I created in the previous posts.
SELECT dbo.fnNthOfNextMonth( CAST('1-24-2004' As DateTime), 5),
dbo.fnNthOfNextMonth2( CAST('1-24-2004' As Date), 5).ToString(),
dbo.fnxNthOfNextMonth( CAST('1-24-2004' As Date), 5).ToString()
All three of these functions give the same result, but each is very different from the others in how it was implemented.
Disclaimer: Since SQL Server “Yukon” is still in Beta 1, features may change between now and when it is actually released as Beta 2 and RTM. Any topic related to SQL Server “Yukon” discussed herein is subject to change without notice. [Hey, are you even reading this?] And although I will try my darnedest to make you aware of any such changes, I cannot guarantee any such notice.