Module 9:Implementing Functions
Overview
Creating and Using FunctionsWorking with FunctionsControlling Execution Context
Lesson 1: Creating and Using Functions
Types of FunctionsWhat Is a Scalar Function?What Is an Inline Table-Valued Function?What Is a Multi-Statement Table-Valued Function?Practice: Creating Functions
Types of Functions
Scalar functions Similar to built-in functions Return a single value
Inline table-valued functions Similar to views with parameters Return a table as the result of single SELECT statement
Multi-statement table-valued functions Similar to stored procedures Return a new table as the result of INSERT statements
What Is a Scalar Function?
RETURNS clause specifies data typeFunction is defined within a BEGIN…END block
Can be invoked anywhere a scalar expression of the same data type is allowed
CREATE FUNCTION Sales.SumSold(@ProductID int) RETURNS int AS BEGIN
DECLARE @ret intSELECT @ret = SUM(OrderQty) FROM Sales.SalesOrderDetail WHERE ProductID = @ProductID IF (@ret IS NULL)
SET @ret = 0RETURN @ret
END
SELECT ProductID, Name, Sales.SumSold(ProductID) AS SumSoldFROM Production.Product
What Is an Inline Table-Valued Function?
RETURNS specifies table as data typeFormat is defined by result setContent of function is a SELECT statement
CREATE FUNCTION HumanResources.EmployeesForManager(@ManagerId int)
RETURNS TABLEASRETURN (
SELECT FirstName, LastNameFROM HumanResources.Employee Employee INNER JOINPerson.Contact Contact ON Employee.ContactID = Contact.ContactIDWHERE ManagerID = @ManagerId )
SELECT * FROM HumanResources.EmployeesForManager(3)-- ORSELECT * FROM HumanResources.EmployeesForManager(6)
What Is a Multi-Statement Table-Valued Function?
RETURNS specifies table data type and defines structureBEGIN and END enclose multiple statements
CREATE FUNCTION HumanResources.EmployeeNames (@format nvarchar(9))
RETURNS @tbl_Employees TABLE(EmployeeID int PRIMARY KEY, [Employee Name] nvarchar(100))
ASBEGIN
IF (@format = 'SHORTNAME')INSERT @tbl_Employees SELECT EmployeeID, LastName FROM HumanResources.vEmployee
ELSE IF (@format = 'LONGNAME')INSERT @tbl_Employees SELECT EmployeeID, (FirstName + ' ' + LastName) FROM HumanResources.vEmployee
RETURNEND
SELECT * FROM HumanResources.EmployeeNames('LONGNAME')
Practice: Creating Functions
In this practice, you will:Create a scalar functionCreate an inline table-valued functionCreate a multi-statementtable-valued functionDrop user-defined functions
Lesson 2: Working with Functions
Guidelines for Creating FunctionsRewriting Stored Procedures as Functions Deterministic and Nondeterministic Functions
Deterministic and Nondeterministic Functions
Deterministic functions Always returns the same value for the same set of
input values and database state Results can be indexed Aggregate and string built-in functions
Nondeterministic functions May return different results for the same set of input
values and database state Results cannot be indexed Configuration, cursor, metadata, security, system
statistics built-in functions
Guidelines for Creating Functions
Determine function type
Create one function for one task
Create, test, and troubleshoot
Qualify object names inside function
Consider ability of SQL Server 2005 to index function results
Rewriting Stored Procedures as Functions
Table-valued functionsSingle SELECT statement with parametersNo update operationsNo need for dynamic EXECUTE statementsBuild intermediate results in to a temporary table
Converting stored procedures to functionsFor single resultset use a table-valued functionFor single scalar value use a scalar function
Lesson 3: Controlling Execution Context
What Is Execution Context? The EXECUTE AS Clause Options for Extending Impersonation ContextDemonstration: Controlling Execution Context
What Is Execution Context?
Sales.Order(Owner: John)
Ted(No permissions)
Function(Owner: Pat)
GetOrders
Ted(EXECUTE permission) Pat
Pat(SELECT permission)
CREATE FUNCTION GetOrders RETURNS TABLEASRETURN ( SELECT * FROM Sales.Order )
CREATE FUNCTION GetOrders RETURNS TABLEWITH EXECUTE AS 'Pat'ASRETURN ( SELECT * FROM Sales.Order )
EXECUTE AS options
The EXECUTE AS Clause
The caller of the module
The person creating or altering the module
The owner of the module
A specified user
CREATE FUNCTION GetOrders RETURNS TABLEWITH EXECUTE AS CALLERASRETURN ( SELECT * FROM Sales.Order )
CREATE FUNCTION GetOrders RETURNS TABLEWITH EXECUTE AS SELFASRETURN ( SELECT * FROM Sales.Order )
CREATE FUNCTION GetOrders RETURNS TABLEWITH EXECUTE AS OWNERASRETURN ( SELECT * FROM Sales.Order )
CREATE FUNCTION GetOrders RETURNS TABLEWITH EXECUTE AS 'Pat'ASRETURN ( SELECT * FROM Sales.Order )
CREATE FUNCTION GetOrders RETURNS TABLEWITH EXECUTE AS { CALLER | SELF | OWNER | user_name }ASRETURN ( SELECT * FROM Sales.Order )
Options for Extending Impersonation Context
EXECUTE AS is restricted to current database by defaultEstablish a trust relationship to extend impersonation to other databases
dboMapped dbo
Signed Code Module
Certificate User
GRANT AUTHENTICATE …SET TRUSTWORTHY ON
Demonstration: Controlling Execution Context
In this demonstration, you will see how to use execution context within a stored procedure
Lab: Implementing Functions
Exercise 1: Creating Functions Exercise 2: Controlling Execution Context