Functions in SQL
Functions in SQL
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:
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
[ListPrice]
FROM production.product
WHERE YEAR([SellStartDate]) BETWEEN @start_year AND @end_year;
RETURN;
GO
EXECUTE
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