Functions in SQL

You might also like

Download as pdf or txt
Download as pdf or txt
You are on page 1of 10

OBJECTIVE:

• SQL SERVER BATCH


• TEMPORARY TABLE/TABLE VARIABLE
• USER-DEFINED FUNCTIONS (UDF)
• STORED PROCEDURES
USER-DEFINED FUNCTIONS (UDF)

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.
USER-DEFINED FUNCTIONS (UDF)

CREATE FUNCTION dbo.fnGetSquare(Number01 INT)


RETURNS INT
CREATE

AS
RETURN Number01 * Number01;
GO
EXECUTE

SELECT dbo.fnGetSquare(5)
GO
USER-DEFINED FUNCTIONS (UDF)

Types of UDFs:
• Scalar-valued
-- accepts parameter(s) and, ultimately, returns a single, atomic
value.
• Table-valued
-- accepts parameter(s) and returns the result in the form of a
table.
This type of function is special because it returns a table that
one can query the results of and join with other tables.
USER-DEFINED FUNCTIONS (UDF)

Scalar-valued Function:

CREATE FUNCTION dbo.fnGetSquare(Number01 INT)


RETURNS INT
CREATE

AS
RETURN Number01 * Number01;
GO
EXECUTE

SELECT dbo.fnGetSquare(5)
GO
USER-DEFINED FUNCTIONS (UDF)
Table-valued Function:
CREATE FUNCTION dbo.udfProductInYear (@start_year INT, @end_year INT)
RETURNS TABLE
AS
RETURN
SELECT [name],
[sellStartDate],
CREATE

[listprice]
FROM production.product
WHERE YEAR([SellStartDate]) BETWEEN @start_year AND @end_year;
GO
EXECUTE

SELECT * FROM dbo. udfProductInYear(2008, 2010)


GO
USER-DEFINED FUNCTIONS (UDF)
Table-valued Function: (cont…)
CREATE FUNCTION dbo.udfProductInYear (@start_year INT, @end_year INT)
RETURNS @FinalTable TABLE ([Name] NVARCHAR(50), [SellStartDate] DATETIME, [ListPrice]
MONEY)
AS
INSERT INTO @FinalTable([Name], [SellStartDate], [ListPrice])
SELECT [Name],
[SellStartDate],
CREATE

[ListPrice]
FROM production.product
WHERE YEAR([SellStartDate]) BETWEEN @start_year AND @end_year;
RETURN;
GO
EXECUTE

SELECT * FROM dbo. udfProductInYear(2008, 2010)


GO
USER-DEFINED FUNCTIONS (UDF)

Advantages:
• Execution Within the SELECT Statement
• Execution from Various Parts of SQL Statements
• UDF Output Can Be Used as a Rowset
• UDFs as Parameterized Views
• Multi-Statement Functions: Alternatives to Stored Procedures
USER-DEFINED FUNCTIONS (UDF)

Disadvantages:

• UDFs are called for each row while used in SELECT statement.
Can hamper performance
USER-DEFINED FUNCTIONS (UDF)

Limitations:
• No Use of Non-deterministic Built-in Functions such as GETDATE(),
RAND()
• Smaller Number of Parameters (1024 in comparison to 2100 of
Procedure)
• Cannot Execute Dynamic SQL
• Cannot Return XML
• Cannot Change SET Options
• Cannot Use Temporary Tables

You might also like