0% found this document useful (0 votes)
17 views

Functions

Uploaded by

zenandecewuka
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
17 views

Functions

Uploaded by

zenandecewuka
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 5

FUNCTIONS

Contents
Functions ................................................................................................................................................. 1
Creating functions ................................................................................................................................... 1
Examples ................................................................................................................................................. 1
References .............................................................................................................................................. 3
Functions
Creates a user-defined function in SQL Server and Azure SQL Database. A user-defined function is a
Transact-SQL or common language runtime (CLR) routine that accepts parameters, performs an
action, such as a complex calculation, and returns the result of that action as a value. The return
value can either be a scalar (single) value or a table.

Creating functions

--Transact-SQL Scalar Function Syntax


CREATE FUNCTION [ schema_name. ] function_name
( [ { @parameter_name parameter_data_type
)
RETURNS return_data_type
BEGIN
function_body
RETURN scalar_expression
END

--Transact-SQL Inline Table-Valued Function Syntax


CREATE FUNCTION [ schema_name. ] function_name
( [ { @parameter_name parameter_data_type
]
)
RETURNS TABLE
[ AS ]
RETURN [ ( ] select_stmt [ ) ]

Examples
The following example creates the user-defined function ISOweek. This function takes a date
argument and calculates the ISO week number. For this function to calculate correctly, SET DATEFIRST
1 must be invoked before the function is called.
The example also shows using the EXECUTE AS clause to specify the security context in which a stored
procedure can be executed. In the example, the option CALLER specifies that the procedure will be
executed in the context of the user that calls it. The other options that you can specify are SELF,
OWNER, and user_name.

IF OBJECT_ID (N'dbo.ISOweek', N'FN') IS NOT NULL


DROP FUNCTION dbo.ISOweek;
GO
CREATE FUNCTION dbo.ISOweek (@DATE datetime)
RETURNS int
WITH EXECUTE AS CALLER
AS
BEGIN
DECLARE @ISOweek int;

1|Page
SET @ISOweek= DATEPART(wk,@DATE)+1
-DATEPART(wk,CAST(DATEPART(yy,@DATE) as CHAR(4))+'0104');
--Special cases: Jan 1-3 may belong to the previous year
IF (@ISOweek=0)
SET @ISOweek=dbo.ISOweek(CAST(DATEPART(yy,@DATE)-1
AS CHAR(4))+'12'+ CAST(24+DATEPART(DAY,@DATE) AS CHAR(2)))+1;
--Special case: Dec 29-31 may belong to the next year
IF ((DATEPART(mm,@DATE)=12) AND
((DATEPART(dd,@DATE)-DATEPART(dw,@DATE))>= 28))
SET @ISOweek=1;
RETURN(@ISOweek);
END;
GO
SET DATEFIRST 1;
SELECT dbo.ISOweek(CONVERT(DATETIME,'12/26/2004',101)) AS 'ISO Week';

The following example returns an inline table-valued function in the AdventureWorks2012 database.
It returns three columns ProductID, Name and the aggregate of year-to-date totals by store as YTD
Total for each product sold to the store.

IF OBJECT_ID (N'Sales.ufn_SalesByStore', N'IF') IS NOT NULL


DROP FUNCTION Sales.ufn_SalesByStore;
GO
CREATE FUNCTION Sales.ufn_SalesByStore (@storeid int)
RETURNS TABLE
AS
RETURN
(
SELECT P.ProductID, P.Name, SUM(SD.LineTotal) AS 'Total'
FROM Production.Product AS P
JOIN Sales.SalesOrderDetail AS SD ON SD.ProductID = P.ProductID
JOIN Sales.SalesOrderHeader AS SH ON SH.SalesOrderID = SD.SalesOrderID
JOIN Sales.Customer AS C ON SH.CustomerID = C.CustomerID
WHERE C.StoreID = @storeid
GROUP BY P.ProductID, P.Name
);
GO

The following is an example of a simple function in SQL (SQL Team, nd):

CREATE FUNCTION whichContinent


(@Country nvarchar(15))
RETURNS varchar(30)
AS
BEGIN
DECLARE @Return varchar(30)
SELECT @return = CASE @Country
WHEN 'Argentina' THEN 'South America'
WHEN 'Belgium' THEN 'Europe'
WHEN 'Brazil' THEN 'South America'
WHEN 'Canada' THEN 'North America'
WHEN 'Denmark' THEN 'Europe'
WHEN 'Finland' THEN 'Europe'
WHEN 'France' THEN 'Europe'
ELSE 'Unknown'
END

2|Page
RETURN @return
END

The following SQL statements will generate the result set shown in the accompanying figure.

print dbo.WhichContinent('USA')
print dbo.WhichContinent('Brazil')
print dbo.WhichContinent('South Africa')
print dbo.WhichContinent('France')

We can also embed the function invocation in a select statement as follows:

SELECT dbo.WhichContinent(Customers.Country), customers.*


FROM customers

The following statement creates a table-valued function which in turn invokes the scalar-valued
function.
CREATE FUNCTION CustomersByContinent
(@Continent varchar(30))
RETURNS TABLE
AS
RETURN
SELECT dbo.WhichContinent(Customers.Country) as continent,
customers.*
FROM customers
WHERE dbo.WhichContinent(Customers.Country) = @Continent

The table-valued function can be invoked as follows:


SELECT * from CustomersbyContinent('North America')
SELECT * from CustomersByContinent('South America')
SELECT * from customersbyContinent('Unknown')

References
1. MSDN Library

3|Page

You might also like