The main benefit of
user-defined functions is that they mean 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, getdate()))
Each time you wanted just the date, with the time
always set to midnight, you would have to perform this same conversion
operation on the result of the getdate() function. As an alternative, you could create a user-defined function that performs the operations on getdate() automatically and always returns the current date, with a time value of midnight, as in this example:
USE bigpubs2008
go
CREATE FUNCTION getonlydate ()
RETURNS datetime
AS
BEGIN RETURN (select convert(datetime, convert(date, getdate())))
END
GO
You could then use the user-defined function in your SQL code in place of the more complex conversion operation on the getdate() function each time. Like the built-in system functions, user-defined functions can be used in SELECT lists, SET clauses of UPDATE statements, VALUES clauses of INSERT statements, as default values, and so on. For example, the following query uses the user-defined function getonlydate() to return the current date, with a time of midnight:
The following examples show how you could use the getonlydate() user-defined function in other statements:
USE bigpubs2008
go
CREATE TABLE Orders (
OrderID int IDENTITY (1, 1) NOT NULL Primary Key,
CustomerID nchar (5) COLLATE SQL_Latin1_General_CP1_CI_AS NULL ,
EmployeeID int NULL ,
OrderDate datetime NULL default dbo.getonlydate(),
RequiredDate datetime NULL ,
ShippedDate datetime NULL
)
go
insert Orders (CustomerID, EmployeeID, RequiredDate)
values ('BERGS', 3, dbo.getonlydate() + 7)
go
update Orders
set ShippedDate = dbo.getonlydate()
where OrderID = 1
go
select OrderDate,
RequiredDate,
ShippedDate
from Orders
where OrderDate = dbo.getonlydate()
go
OrderDate RequiredDate ShippedDate
----------------------- ----------------------- -----------------------
2008-06-03 00:00:00.000 2008-06-10 00:00:00.000 2008-06-03 00:00:00.000
If you use the getonlydate() function consistently when you want to store only dates with a time value of midnight, searching against datetime columns is easier because you don’t have to concern yourself with the time component. For example, if you use getdate() instead of getonlydate(), you have to account for the time component in your queries against OrderDate to ensure that you find all records for a particular day:
SELECT OrderDate,
RequiredDate,
ShippedDate
from Orders
where OrderDate >= convert(varchar(10), getdate(), 110)
and OrderDate < convert(varchar(10), getdate() + 1, 110)
From this example, you can see how much using the getonlydate() user-defined function can simplify your queries.
Tip
Another way to avoid the issues related to storing a
time component in your date-valued columns in SQL Server 2008 is to use
the new DATE data type instead of DATETIME.
In addition to functions that return scalar values,
you can also define functions that return table results. You can use
functions that return table results anywhere in queries that a table or
view can be used, including joins, subqueries, and so on. The following
examples show how to use a user-defined table-valued function that
returns a list of valid book types:
use bigpubs2008
go
create function valid_book_types()
returns TABLE
as
return (SELECT distinct type from titles)
go
select * from dbo.valid_book_types()
go
insert titles
select * from newtitles
where type in (select * from dbo.valid_book_types())
Essentially, this example reduces a query to a simple function that you can now use anywhere a table can be referenced.
With a few restrictions—you can write all types of functions in SQL Server to perform
various calculations or routines. For example, you could create a T-SQL
function that returns a valid list of code values, a function to
determine the number of days items are backordered, a function to return
the average price of all books, and so on. Plus, with the capability to
create CLR-based functions, you can create significantly more powerful functions than what can be accomplished using T-SQL alone. Examples of CLR-based functions include a more robust soundex()
function, a function to return the factorial of a number, and an
address comparison function. The possibilities are nearly endless. As
you have can see, user-defined functions significantly increase the
capabilities and flexibility of T-SQL.