Presentation is loading. Please wait.

Presentation is loading. Please wait.

Module 9 Designing and Implementing Stored Procedures.

Similar presentations


Presentation on theme: "Module 9 Designing and Implementing Stored Procedures."— Presentation transcript:

1 Module 9 Designing and Implementing Stored Procedures

2 Module Overview Introduction to Stored Procedures Working with Stored Procedures Implementing Parameterized Stored Procedures Controlling Execution Context

3 Lesson 1: Introduction to Stored Procedures What is a Stored Procedure? Benefits of Stored Procedures Working with System Stored Procedures Statements not Permitted Demonstration 1A: Working with System Stored Procedures and Extended Stored Procedures

4 What is a Stored Procedure? When applications interact with SQL Server, there are two basic ways to execute T-SQL code:  Every statement can be issued directly by the application  Groups of statements can be stored on the server as stored procedures and given a name. The application then calls the procedures by name. Stored procedures  Are similar to procedures or methods in other languages  Can have input parameters  Can have output parameters  Can return sets of rows  Are executed by the EXECUTE T-SQL statement  Can be created in managed code or T-SQL

5 Benefits of Stored Procedures Can enhance the security of an application as they are a security boundary  Users can be given permission to execute a stored procedure without permission to the objects it accesses Allow for modular programming  Create once, call many times and from many applications Allow for delayed binding of objects  Can create a stored procedure that references a database object that doesn't exist yet.  Can avoid the need for ordering in object creation Can improve performance  Single statement requested across the network can execute hundreds of lines of T-SQL code  Better opportunities for execution plan reuse

6 Working with System Stored Procedures Large number of system stored procedures is supplied with SQL Server Two basic types of system stored procedure:  System Stored Procedures – typically used for administrative purposes to either configure servers, databases or objects or to view information about them.  System Extended Stored Procedures – extend the functionality of SQL Server. Key difference is how they are coded:  System Stored Procedures are T-SQL code in the master database  System Extended Stored Procedures are references to DLLs

7 Statements not Permitted Not all T-SQL statements are permitted in stored procedures. In particular, the following list are not permitted: Statements not permitted CREATE AGGREGATECREATE RULE CREATE DEFAULTCREATE SCHEMA CREATE or ALTER FUNCTIONCREATE or ALTER TRIGGER CREATE or ALTER PROCEDURECREATE or ALTER VIEW SET PARSEONLYSET SHOWPLAN_ALL SET SHOWPLAN_TEXTSET SHOWPLAN_XML USE databasename

8 Demonstration 1A: Working with System Stored Procedures and Extended Stored Procedures In this demonstration you will see: How to execute system stored procedures How to execute system extended stored procedures

9 Lesson 2: Working with Stored Procedures Creating a Stored Procedure Executing Stored Procedures Altering a Stored Procedure Dropping a Stored Procedure Stored Procedure Dependencies Guidelines for Creating Stored Procedures Obfuscating Stored Procedure Definitions Demonstration 2A: Stored Procedures

10 Creating a Stored Procedure CREATE PROCEDURE Sales.GetSalespersonNames AS SELECT s.BusinessEntityID, p.LastName, p.FirstName FROM Sales.Salesperson AS s INNER JOIN Person.Person AS p ON s.BusinessEntityID = p.BusinessEntityID WHERE s.TerritoryID IS NOT NULL ORDER BY s.BusinessEntityID; CREATE PROCEDURE Sales.GetSalespersonNames AS SELECT s.BusinessEntityID, p.LastName, p.FirstName FROM Sales.Salesperson AS s INNER JOIN Person.Person AS p ON s.BusinessEntityID = p.BusinessEntityID WHERE s.TerritoryID IS NOT NULL ORDER BY s.BusinessEntityID; CREATE PROCEDURE is used to create new stored procedures The procedure must not already exist, otherwise ALTER must be used or the procedure dropped first CREATE PROCEDURE must be the only statement in a batch

11 Executing Stored Procedures EXEC Sales.GetSalespersonNames; EXECUTE statement:  Used to execute stored procedures and other objects such as dynamic SQL statements stored in a string  Can execute system stored procedures (sp_ prefix) from within the master database without having to refer to that database. Use two part naming when executing local stored procedures within a database. Otherwise, SQL Server searches for the procedure:  In the sys schema of the current database  In the caller's default schema in the current database  In the dbo schema in the current database

12 Altering a Stored Procedure ALTER PROCEDURE Sales.GetSalespersonNames AS SELECT s.BusinessEntityID, p.LastName, p.FirstName FROM Sales.Salesperson AS s INNER JOIN Person.Person AS p ON s.BusinessEntityID = p.BusinessEntityID WHERE s.TerritoryID IS NOT NULL AND s.SalesQuota IS NOT NULL ORDER BY s.BusinessEntityID; ALTER PROCEDURE Sales.GetSalespersonNames AS SELECT s.BusinessEntityID, p.LastName, p.FirstName FROM Sales.Salesperson AS s INNER JOIN Person.Person AS p ON s.BusinessEntityID = p.BusinessEntityID WHERE s.TerritoryID IS NOT NULL AND s.SalesQuota IS NOT NULL ORDER BY s.BusinessEntityID; ALTER PROCEDURE  Used to replace a stored procedure  Retains the existing permissions on the procedure

13 Dropping a Stored Procedure SELECT SCHEMA_NAME(schema_id) AS SchemaName, name AS ProcedureName FROM sys.procedures; GO DROP PROCEDURE Sales.GetSalespersonNames; SELECT SCHEMA_NAME(schema_id) AS SchemaName, name AS ProcedureName FROM sys.procedures; GO DROP PROCEDURE Sales.GetSalespersonNames; DROP PROCEDURE removes one or more stored procedures from the current database Find the list of existing procedures in the current database by querying the sys.procedures system view Use sp_dropextendedproc to drop Extended Stored Procedures

14 Stored Procedure Dependencies New system views replace the use of sp_depends sys.sql_expression_dependencies  Contains one row per by-name dependency on a user-defined entities in the current database sys.dm_sql_referenced_entities  Contains one row for each entity referenced by another entity sys.dm_sql_referencing_entities  Contains one row for each entity referencing another entity

15 Guidelines for Creating Stored Procedures Qualify names inside of stored procedures Keep consistent SET options Apply consistent naming conventions (and no sp_ prefix) Use @@nestlevel to see current nesting level (32 max) Keep one procedure per task

16 Obfuscating Stored Procedure Definitions WITH ENCRYPTION clause  Encrypts stored procedure definition stored in SQL Server  Protects stored procedure creation logic to a limited extent  Is generally not recommended CREATE PROCEDURE HumanResources.EmployeeList WITH ENCRYPTION AS SELECT EmployeeID, LastName, FirstName FROM HumanResources.Employee; CREATE PROCEDURE HumanResources.EmployeeList WITH ENCRYPTION AS SELECT EmployeeID, LastName, FirstName FROM HumanResources.Employee; Use WITH ENCRYPTION on ALTER PROC to retain encryption

17 Demonstration 2A: Stored Procedures In this demonstration, you will see: How to create a stored procedure How to execute a stored procedure How to create a stored procedure that returns multiple rowsets How to alter a stored procedure How to view the list of stored procedures

18 Lesson 3: Implementing Parameterized Stored Procedures Working with Parameterized Stored Procedures Using Input Parameters Using Output Parameters Parameter Sniffing and Performance Demonstration 3A: Stored Procedure Parameters

19 Working with Parameterized Stored Procedures Input parameters Output parameters Return values Parameterized stored procedures contain 3 major components:

20 Using Input Parameters CREATE PROCEDURE Sales.OrdersByDueDateAndStatus @DueDate datetime, @Status tinyint = 5 AS SELECT soh.SalesOrderID,soh.OrderDate,soh.CustomerID FROM Sales.SalesOrderHeader AS soh WHERE soh.DueDate = @DueDate AND soh.[Status] = @Status ORDER BY soh.SalesOrderID; GO EXEC Sales.OrdersByDueDateAndStatus '20050713',5; EXEC Sales.OrdersByDueDateAndStatus '20050713'; EXEC Sales.OrdersByDueDateAndStatus @DueDate = '20050713', @Status = 5; CREATE PROCEDURE Sales.OrdersByDueDateAndStatus @DueDate datetime, @Status tinyint = 5 AS SELECT soh.SalesOrderID,soh.OrderDate,soh.CustomerID FROM Sales.SalesOrderHeader AS soh WHERE soh.DueDate = @DueDate AND soh.[Status] = @Status ORDER BY soh.SalesOrderID; GO EXEC Sales.OrdersByDueDateAndStatus '20050713',5; EXEC Sales.OrdersByDueDateAndStatus '20050713'; EXEC Sales.OrdersByDueDateAndStatus @DueDate = '20050713', @Status = 5; Parameters  Have @ prefix, data type, can have a default value  Can be passed in order or can be passed by name (but no combination of these is permitted in one statement) Validate input parameters early in stored procedure code

21 Using Output Parameters CREATE PROC Sales.GetOrderCountByDueDate @DueDate datetime, @OrderCount int OUTPUT AS SELECT @OrderCount = COUNT(1) FROM Sales.SalesOrderHeader AS soh WHERE soh.DueDate = @DueDate; GO DECLARE @DueDate datetime = '20050713'; DECLARE @OrderCount int; EXEC Sales.GetOrderCountByDueDate @DueDate, @OrderCount OUTPUT; SELECT @OrderCount; CREATE PROC Sales.GetOrderCountByDueDate @DueDate datetime, @OrderCount int OUTPUT AS SELECT @OrderCount = COUNT(1) FROM Sales.SalesOrderHeader AS soh WHERE soh.DueDate = @DueDate; GO DECLARE @DueDate datetime = '20050713'; DECLARE @OrderCount int; EXEC Sales.GetOrderCountByDueDate @DueDate, @OrderCount OUTPUT; SELECT @OrderCount; OUTPUT must be specified:  When declaring the parameter  When executing the stored procedure

22 Parameter Sniffing and Performance Query plan generated for a stored procedure is mostly reused the next time the stored procedure is executed In general, this is very desirable behavior Some stored procedures need to have very different query plans for different sets of parameters before they will perform optimally  Problem is commonly called a "parameter sniffing" problem Options for resolving  CREATE PROC xyz WITH RECOMPILE  sp_recompile 'xyz'  EXEC WITH RECOMPILE  OPTION (OPTIMIZE FOR)

23 Demonstration 3A: Stored Procedure Parameters In this demonstration you will see: How to create a stored procedure with parameters How to alter a stored procedure with parameters to correct a common stored procedure bug

24 Lesson 4: Controlling Execution Context Controlling Execution Context The EXECUTE AS Clause Viewing Execution Context Demonstration 4A: Viewing Execution Context

25 Controlling Execution Context Sales.SalesOrderHeader (Owner: John) Sales.SalesOrderHeader (Owner: John) Ted (No permissions) Ted (No permissions) Procedure (Owner: Pat) Procedure (Owner: Pat) GetOrderCountByDueDate Ted (EXECUTE permission) Ted (EXECUTE permission) Pat (SELECT permission) Pat (SELECT permission) CREATE PROC Sales.GetOrderCountByDueDate @DueDate datetime, @OrderCount int OUTPUT AS SELECT @OrderCount = COUNT(1) FROM Sales.SalesOrderHeader AS soh WHERE soh.DueDate = @DueDate; CREATE PROC Sales.GetOrderCountByDueDate @DueDate datetime, @OrderCount int OUTPUT AS SELECT @OrderCount = COUNT(1) FROM Sales.SalesOrderHeader AS soh WHERE soh.DueDate = @DueDate; CREATE PROC Sales.GetOrderCountByDueDate @DueDate datetime, @OrderCount int OUTPUT WITH EXECUTE AS 'Pat' AS SELECT @OrderCount = COUNT(1) FROM Sales.SalesOrderHeader AS soh WHERE soh.DueDate = @DueDate; CREATE PROC Sales.GetOrderCountByDueDate @DueDate datetime, @OrderCount int OUTPUT WITH EXECUTE AS 'Pat' AS SELECT @OrderCount = COUNT(1) FROM Sales.SalesOrderHeader AS soh WHERE soh.DueDate = @DueDate;

26 The EXECUTE AS Clause Enables Impersonation Provides access to modules via impersonation Can be used to impersonate server-level principals or logins via the EXECUTE AS LOGIN statement Can be used to impersonate database level principals or users via the EXECUTE AS USER statement CREATE PROCEDURE Sales.GetOrders WITH EXECUTE AS {CALLER | SELF | OWNER | ‘user_name’ } AS … CREATE PROCEDURE Sales.GetOrders WITH EXECUTE AS {CALLER | SELF | OWNER | ‘user_name’ } AS …

27 Viewing Execution Context Details of the current security context can be viewed programmatically  sys.login_token shows the login-related details  sys.user_token shows the user-related details

28 Demonstration 4A: Viewing Execution Context In this demonstration you will see: How to view details of execution context How to change execution context for a session How to use the WITH EXECUTE AS clause in a stored procedure

29 Lab 9: Designing and Implementing Stored Procedures Exercise 1: Create stored procedures Exercise 2: Create a parameterized stored procedure Challenge Exercise 3: Alter the execution context of stored procedures (Only if time permits) Logon information Estimated time: 45 minutes

30 Lab Scenario You need to create a set of stored procedures to support a new reporting application. The procedures will be created within a new Reports schema.

31 Lab Review When is the OUTPUT keyword needed for output parameters in working with stored procedures? What does the sys.login_token view show?

32 Module Review and Takeaways Review Questions Best Practices


Download ppt "Module 9 Designing and Implementing Stored Procedures."

Similar presentations


Ads by Google