Why Use User-Defined Functions?

The main benefit of user-defined functions is that you are not limited to just the functions SQL Server provides. You can develop your own functions to meet your specific needs or to simplify complex SQL code. For example, the getdate() function returns the current system date and time. It always includes both a date component and time component, with accuracy down to the milliseconds. What if you wanted to return a datetime value with just the date and have the time always set to midnight? To do this, you would have to pass the result from getdate() through some other functions to zero out the time component. The following is one possible solution:

select convert(datetime, convert(date, ...

Get Microsoft® SQL Server 2012 Unleashed now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.