This is a great question! A user defined function is a subroutine that encapsulates a piece of logic that can be reused. At a high level functions are either deterministic or nondeterministic which means they either return the same value with the same input values each time the function is called or not. SQL Server ships with a number of date and time functions that may address your needs. These functions include: GETDATE, DATEADD, DATEDIFF, DATEPART, etc. I would recommend reviewing these links to create your own user defined function to meet your specific application needs!
For More Information
- Dozens more answers to tough SQL Server questions from Greg Robidoux and Jeremy Kadlec are available here.
- The Best Microsoft SQL Server Web Links: tips, tutorials, scripts, and more.
- Have a SQL Server tip to offer your fellow DBAs and developers? The best tips submitted will receive a cool prize. Submit your tip today!
- Ask your technical SQL Server questions -- or help out your peers by answering them -- in our live discussion forums.
- Ask the Experts yourself: Our SQL, database design, SQL Server, DB2, object-oriented and data warehousing gurus are waiting to answer your toughest questions.
This was first published in May 2004