18
Module 9: Implementing Functions

Module 9: Implementing Functions

  • Upload
    dava

  • View
    45

  • Download
    3

Embed Size (px)

DESCRIPTION

Module 9: Implementing Functions. Overview. Creating and Using Functions Working with Functions Controlling Execution Context. Lesson 1: Creating and Using Functions . Types of Functions What Is a Scalar Function? What Is an Inline Table-Valued Function? - PowerPoint PPT Presentation

Citation preview

Page 1: Module 9: Implementing Functions

Module 9:Implementing Functions

Page 2: Module 9: Implementing Functions

Overview

Creating and Using FunctionsWorking with FunctionsControlling Execution Context

Page 3: Module 9: Implementing Functions

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

Page 4: Module 9: Implementing 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

Page 5: Module 9: Implementing Functions

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

Page 6: Module 9: Implementing Functions

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)

Page 7: Module 9: Implementing Functions

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')

Page 8: Module 9: Implementing Functions

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

Page 9: Module 9: Implementing Functions

Lesson 2: Working with Functions

Guidelines for Creating FunctionsRewriting Stored Procedures as Functions Deterministic and Nondeterministic Functions

Page 10: Module 9: Implementing 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

Page 11: Module 9: Implementing 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

Page 12: Module 9: Implementing Functions

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

Page 13: Module 9: Implementing Functions

Lesson 3: Controlling Execution Context

What Is Execution Context? The EXECUTE AS Clause Options for Extending Impersonation ContextDemonstration: Controlling Execution Context

Page 14: Module 9: Implementing Functions

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 )

Page 15: Module 9: Implementing Functions

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 )

Page 16: Module 9: Implementing Functions

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

Page 17: Module 9: Implementing Functions

Demonstration: Controlling Execution Context

In this demonstration, you will see how to use execution context within a stored procedure

Page 18: Module 9: Implementing Functions

Lab: Implementing Functions

Exercise 1: Creating Functions Exercise 2: Controlling Execution Context