0% found this document useful (0 votes)
15 views6 pages

Tutorial USD

Uploaded by

bob.ilukhor
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
15 views6 pages

Tutorial USD

Uploaded by

bob.ilukhor
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 6

Lecturer : Damien Kettle Database Administration

Tutorial – User Defined Functions


Overview
In the simplest terms, a user-defined function (UDF) in SQL Server is a programming construct that
accepts parameters, does work that typically makes use of the accepted parameters, and returns a
type of result. This tutorial will cover two types of UDFs: scalar-valued and table-valued.

Scalar Functions
Scalar functions return a single value of the type defined in the RETURNS clause. The body of the
function is between a BEGIN and END block.

Example 1
The following statement shows how to create a function that accepts two input parameters, sums
them together and then returns the sum to the calling statement.

Create the UDF below on your Student Database:

CREATE FUNCTION udf_SumTwoValues


(@Val1 int, @Val2 int)
RETURNS int
AS
BEGIN
RETURN (@Val1+@Val2)
END

The structure of the CREATE FUNCTION statement is fairly straightforward. You provide an object
name (udf_SumTwoValues), input parameters (@Val1 and @Val2), the type of data the function will
return () and the statement(s) the function executes are located between the BEGIN…END block. The
following SELECT statement calls the function. Note that the two-part name (owner.object_name) is
required when calling this function.

SELECT dbo.udf_SumTwoValues(1,2) AS SumOfTwoValues

When the SELECT is executed, the input parameters 1 and 2 are added together and the sum 3 is
returned. You can use any values that either are, or can be, implicitly converted to an int data type
for the input parameters. Keep in mind, though, that only an int can be returned, so the following
statement will not produce the desired results.

SELECT dbo.udf_SumTwoValues(1.98,2.78) AS SumOfTwoValues

The function returns a 3, which indicates the decimal portion of the parameters are truncated before
the calculation occurs.
Lecturer : Damien Kettle Database Administration

Example 2
Before you start this Example set up the SalesHistory table and load data into it:

CREATE TABLE dbo.SalesHistory


(
SaleID int IDENTITY(1,1) NOT NULL PRIMARY KEY,
Product varchar(10) NULL,
SaleDate datetime NULL,
SalePrice decimal(38, 2) NULL
)

DECLARE @i SMALLINT
SET @i = 1

WHILE (@i <=1000)


BEGIN

INSERT INTO SalesHistory(Product, SaleDate, SalePrice)


VALUES ('Computer', DATEADD(mm, @i, '3/11/1919'), DATEPART(ms, GETDATE())
+ (@i + 57))

INSERT INTO SalesHistory(Product, SaleDate, SalePrice)


VALUES('BigScreen', DATEADD(mm, @i, '3/11/1927'), DATEPART(ms, GETDATE())
+ (@i + 13))

INSERT INTO SalesHistory(Product, SaleDate, SalePrice)


VALUES('PoolTable', DATEADD(mm, @i, '3/11/1908'), DATEPART(ms, GETDATE())
+ (@i + 29))

SET @i = @i + 1
END

The script below defines a function named dbo.udf_GetProductSales that accepts three parameters
and returns a DECIMAL value. The function uses the three input parameters as criteria in calculating
the total sales from the SalesHistory table.

CREATE FUNCTION dbo.udf_GetProductSales


(
@Product VARCHAR(10),
@BeginDate DATETIME,
@EndDate DATETIME
)
RETURNS DECIMAL(10, 2)
AS
BEGIN
DECLARE @Sales DECIMAL(10, 2)

SELECT @Sales = SUM(SalePrice)


FROM SalesHistory
WHERE Product = @Product
AND SaleDate BETWEEN @BeginDate AND @EndDate

RETURN(@Sales)
END
Lecturer : Damien Kettle Database Administration

The script below calls the UDF created in the above script. Note: The schema the function belongs
to must be used in the call. In this case, the function belongs to the dbo schema.

SELECT dbo.udf_GetProductSales('PoolTable', '1/1/1990', '1/1/2000')


Lecturer : Damien Kettle Database Administration

Table Valued Scalar Functions


As their name implies, inline table-valued functions return a table. Inline table-valued functions have
no body. They simply return the result of a simple SELECT statement. Here's an example:

Example 1
Use below DDL statement to create a Contacts table:

CREATE TABLE dbo.Contacts


(ContactId int IDENTITY(1,1) NOT NULL PRIMARY KEY,
FirstName varchar(50) NOT NULL,
LastName varchar(50) NOT NULL,
City varchar(20) NOT NULL,
Country varchar(20) NOT NULL,
JobTitle varchar(20) NOT NULL,
)

Use below DML statement to insert some data into the Contacts table:

INSERT INTO dbo.Contacts


(FirstName, LastName, City, Country, JobTitle)
VALUES
('Chris', 'Harris', 'London', 'United Kingdom', 'Editor'),
('Mark', 'Shaw', 'Dublin', 'Ireland', 'Designer'),
('Colm', 'Brady', 'Cork', 'Ireland', 'Manager'),
('Sam', 'Lynch', 'Cork', 'Ireland', 'Director'),
('Jason', 'Barlowe', 'London', 'United Kingdom', 'Editor')
Lecturer : Damien Kettle Database Administration

Create the below User Defined Function by copying and pasting the SQL code into SQL Server
Management Studio and clicking Execute:

CREATE FUNCTION dbo.udf_GetContactByTitle


(@Title varchar(20))
RETURNS Table
AS
RETURN
SELECT
FirstName,
LastName,
City,
Country,
JobTitle
FROM
dbo.Contacts
WHERE
JobTitle = @Title

After creating this you will see the new UDF under the Functions -> Table-valued Functions folder:

This example receives a parameter called @Title. It returns a table containing selected fields from
the Contacts table where the JobTitle equals the @Title parameter value. You would call the
function like this:

SELECT * FROM dbo.udf_GetContactByTitle('Editor')

You should get back a result set similar to below:


Lecturer : Damien Kettle Database Administration

Example 2
The following function accepts the particular product for which we were searching, along with the
SaleID from the SalesHistory table. From the function definition, you can see that the function
returns a table named @SalesTable that contains two columns: SalesTotal and SalesCount. The body
of the function inserts aggregate values into the @SalesTable table variable based upon the input
parameters.

CREATE FUNCTION dbo.udf_GetProductSalesTable


(
@Product VARCHAR(10),
@SaleID INT
)
RETURNS @SalesTable TABLE
(
SalesTotal DECIMAL(10, 2),
SalesCount INT
)

BEGIN

INSERT INTO @SalesTable(SalesTotal, SalesCount)


SELECT
SUM(SalePrice), COUNT(SaleID)
FROM
SalesHistory
WHERE
Product = @Product AND
SaleID <= @SaleID

RETURN
END
GO

The following code uses the APPLY operator to invoke the table-valued function with the values from
the SalesHistory table.

SELECT * FROM SalesHistory sh


CROSS APPLY dbo.udf_GetProductSalesTable(sh.Product, sh.SaleID)
ORDER BY sh.SaleID ASC

You might also like