IT tutorials
 
Database
 

SQL Server 2008 R2 : Why Use User-Defined Functions?

1/29/2013 4:15:23 PM
- Free product key for windows 10
- Free Product Key for Microsoft office 365
- Malwarebytes Premium 3.7.1 Serial Keys (LifeTime) 2019

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:

select dbo.getonlydate()

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.

 
Others
 
 
 
Top 10
 
- Microsoft Visio 2013 : Adding Structure to Your Diagrams - Finding containers and lists in Visio (part 2) - Wireframes,Legends
- Microsoft Visio 2013 : Adding Structure to Your Diagrams - Finding containers and lists in Visio (part 1) - Swimlanes
- Microsoft Visio 2013 : Adding Structure to Your Diagrams - Formatting and sizing lists
- Microsoft Visio 2013 : Adding Structure to Your Diagrams - Adding shapes to lists
- Microsoft Visio 2013 : Adding Structure to Your Diagrams - Sizing containers
- Microsoft Access 2010 : Control Properties and Why to Use Them (part 3) - The Other Properties of a Control
- Microsoft Access 2010 : Control Properties and Why to Use Them (part 2) - The Data Properties of a Control
- Microsoft Access 2010 : Control Properties and Why to Use Them (part 1) - The Format Properties of a Control
- Microsoft Access 2010 : Form Properties and Why Should You Use Them - Working with the Properties Window
- Microsoft Visio 2013 : Using the Organization Chart Wizard with new data
Technology FAQ
- Is possible to just to use a wireless router to extend wireless access to wireless access points?
- Ruby - Insert Struct to MySql
- how to find my Symantec pcAnywhere serial number
- About direct X / Open GL issue
- How to determine eclipse version?
- What SAN cert Exchange 2010 for UM, OA?
- How do I populate a SQL Express table from Excel file?
- code for express check out with Paypal.
- Problem with Templated User Control
- ShellExecute SW_HIDE
programming4us programming4us