Download presentation
Presentation is loading. Please wait.
1
Designing and Implementing Stored Procedures
20762B 9: Designing and Implementing Stored Procedures Module 9 Designing and Implementing Stored Procedures
2
Controlling Execution Context
20762B Module Overview 9: Designing and Implementing Stored Procedures Controlling Execution Context
3
Lesson 1: Introduction to Stored Procedures
20762B Lesson 1: Introduction to Stored Procedures 9: Designing and Implementing Stored Procedures Demonstration: Working with System Stored Procedures and Extended Stored Procedures Question The system stored procedure prefix (sp_) and the extended stored procedure prefix (xp_) have become a little muddled over time. What does this say about the use of prefixes when naming objects like stored procedures? Answer Prefixes that attempt to indicate the function of an object are not recommended. A well thought out and implemented naming convention is a much better way of naming stored procedures.
4
What Is a Stored Procedure?
20762B What Is a Stored Procedure? 9: Designing and Implementing Stored Procedures When applications interact with SQL Server, there are two basic ways to execute Transact-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 Transact-SQL statement Can be created in managed code or Transact-SQL
5
Benefits of Stored Procedures
9: Designing and Implementing Stored Procedures Can enhance the security of an application Users can be given permission to execute a stored procedure without permission to the objects that it accesses Enables modular programming Create once, but call many times and from many applications Enables the delayed binding of objects Can create a stored procedure that references a database object that does not exist yet Can avoid the need for ordering in object creation Can improve performance A single statement requested across the network can execute 100s of lines of Transact-SQL code Better opportunities for execution plan reuse
6
Working with System Stored Procedures
20762B Working with System Stored Procedures 9: Designing and Implementing Stored Procedures A large number of system stored procedures are supplied with SQL Server Two basic types of system stored procedure System stored procedures: typically used for administrative purposes either to 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 Transact-SQL code in the master database System extended stored procedures are references to DLLs Stress that user extended stored procedures are now deprecated. Replacements written in managed code via SQL Server CLR Integration should be used instead. Emphasize that whilst system stored procedures originally had the prefix sp_ and system extended stored procedures had the prefix xp_, the naming has become muddled over the years. This is a good argument against prefixes in general as an incorrect prefix can be much worse than no prefix at all. Do not, in any circumstances, use sp_ and xp_ for user stored procedures.
7
Statements Not Permitted in Stored Procedures
20762B Statements Not Permitted in Stored Procedures 9: Designing and Implementing Stored Procedures Some Transact-SQL statements are not allowed: CREATE AGGREGATE CREATE DEFAULT CREATE or ALTER FUNCTION CREATE or ALTER PROCEDURE SET PARSEONLY SET SHOWPLAN TEXT USE databasename CREATE RULE CREATE SCHEMA CREATE or ALTER TRIGGER CREATE or ALTER VIEW SET SHOWPLAN ALL or SET SHOWPLAN XML Stress that most Transact-SQL statements can be used within the bodies of stored procedures. Those that cannot be used normally relate to one of the following actions: Creation of other objects. Changing SET options that relate to query plans. Changing database context via the USE statement.
8
In this demonstration, you will see how to:
20762B Demonstration: Working with System Stored Procedures and Extended Stored Procedures 9: Designing and Implementing Stored Procedures In this demonstration, you will see how to: Execute system stored procedures Preparation Steps Start the 20762B-MIA-DC and 20762B-MIA-SQL virtual machines. Demonstration Steps Ensure that the 20762B-MIA-DC and 20762B-MIA-SQL virtual machines are running, and then log on to 20762B-MIA-SQL as ADVENTUREWORKS\Student with the password Pa$$w0rd. Navigate to the folder D:\Demofiles\Mod09 and execute Setup.cmd as an administrator. In the User Account Control dialog box, click Yes. Start SQL Server Management Studio and connect to the MIA-SQL instance using Windows authentication. In SQL Server Management Studio, open the file D:\Demofiles\Mod09\Module09.ssmssln. In Solution Explorer, in the Queries folder, double-click the 11 - Demonstration1A.sql script file. Highlight the text under the comment Step 1 - Switch to the AdventureWorks database, and click Execute. Highlight the text under the comment Step 2 - Execute the sp_configure system stored procedure, and click Execute. Highlight the text under the comment Step 3 - Execute the xp_dirtree extended system stored procedure, and click Execute. Keep SQL Server Management Studio open for the next demo.
9
Lesson 2: Working with Stored Procedures
20762B Lesson 2: Working with Stored Procedures 9: Designing and Implementing Stored Procedures Demonstration: Stored Procedures Question Obfuscating the body of a stored procedure is best avoided, but when might you want to use this functionality? ( )Option 1: When transferring the stored procedure between servers. ( )Option 2: When ing the stored procedure code to a colleague. ( )Option 3: When the stored procedure takes input parameters that should not be disclosed. ( )Option 4: When the stored procedure contains intellectual property that needs protecting. Answer (√) Option -2: When the stored procedure contains intellectual property that needs protecting.
10
Creating a Stored Procedure
20762B Creating a Stored Procedure 9: Designing and Implementing Stored Procedures 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 Some students may ask questions about CREATE OR ALTER PROCEDURE statements. If this subject arises, mention that there is no SQL Server equivalent to this at present. The way this is usually addressed in SQL Server is to write a script that drops the procedure if it already exists. The downside of this is that permissions are lost. Because the CREATE PROCEDURE and the ALTER PROCEDURE both need to be the only statements in a batch, there is no easy option for using logic to decide whether to create or alter the procedure.
11
Executing a Stored Procedure
20762B Executing a Stored Procedure 9: Designing and Implementing Stored Procedures EXECUTE statement Used to execute stored procedures and other objects such as dynamic SQL statements stored in a string Use two- or three-part naming when executing stored procedures to avoid SQL Server having to carry out unnecessary searches Walk the students through the concept of where SQL Server goes to locate stored procedures. Stress the importance of using two- and three-part naming conventions.
12
Altering a Stored Procedure
20762B Altering a Stored Procedure 9: Designing and Implementing Stored Procedures ALTER PROCEDURE statement Used to replace a stored procedure Retains the existing permissions on the procedure
13
Dropping a Stored Procedure
20762B Dropping a Stored Procedure 9: Designing and Implementing Stored Procedures DROP PROCEDURE removes one or more stored procedures from the current database sys.procedures system view gives details on stored procedures in the current database sp_dropextendedproc to drop system extended stored procedures
14
Stored Procedures Error Handling
20762B Stored Procedures Error Handling 9: Designing and Implementing Stored Procedures Include error handling in your stored procedures Use the TRY … CATCH construct to handle errors BEGIN TRY <code> END TRY BEGIN CATCH <error handling code> END CATCH Error functions used within a CATCH block ERROR_NUMBER() ERROR_SEVERITY() ERROR_STATE() ERROR_PROCEDURE() ERROR_LINE() ERROR_MESSAGE()
15
Transaction Handling Explicit transactions are managed with
20762B Transaction Handling 9: Designing and Implementing Stored Procedures Explicit transactions are managed with BEGIN TRANSACTION or BEGIN TRAN COMMIT TRANSACTION Use a TRY … CATCH block to ROLLBACK transactions Use to ensure the complete transaction—or nothing—is committed keeps count of the number of BEGIN TRANSACTIONS Use SET XACT_ABORT ON or OFF to determine how SQL Server should handle statements within a transaction
16
Stored Procedure Dependencies
20762B Stored Procedure Dependencies 9: Designing and Implementing Stored Procedures New system views replace the use of sp_depends sys.sql_expression_dependencies Contains one row per dependency by name on 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 Reiterate to students that the sys.sql_expression_dependencies view replaces the sp_depends system stored procedure that was known to be unreliable, as it had no understanding of partial dependencies.
17
Guidelines for Creating Stored Procedures
20762B Guidelines for Creating Stored Procedures 9: Designing and Implementing Stored Procedures Qualify names inside stored procedures Keep consistent SET options SET NOCOUNT ON Apply consistent naming conventions (and no sp_ prefix) Use to see current nesting level (32 is the maximum number of levels) Use return codes to identify reasons various execution outcomes Keep to one procedure for each task
18
Obfuscating Stored Procedures
9: Designing and Implementing Stored Procedures WITH ENCRYPTION clause Encrypts stored procedure definition stored in SQL Server Protects stored procedure creation logic to a limited extent Is generally not recommended
19
Demonstration: Stored Procedures
20762B Demonstration: Stored Procedures 9: Designing and Implementing Stored Procedures In this demonstration, you will see how to: Create, execute, and alter a stored procedure Preparation Steps Ensure that the 20762B-MIA-DC and 20762B-MIA-SQL virtual machines are running and that you have completed the previous demo in this module. Demonstration Steps In Solution Explorer, in the Queries folder, double-click the 21 - Demonstration2A.sql script file. Highlight the code under the comment Step 1 - Switch to the AdventureWorks database, and click Execute. Highlight the code under the comment Step 2 - Create the GetBlueProducts stored procedure, and click Execute. Highlight the code under the comment Step 3 - Execute the GetBlueProducts stored procedure, and click Execute. Highlight the code under the comment Step 4 - Create the GetBlueProductsAndModels stored procedure, and click Execute. Highlight the code under the comment Step 5 - Execute the GetBlueProductsAndModels stored procedure which returns multiple rowsets, and click Execute. Highlight the code under the comment Step 6 - Alter the procedure because the 2nd query does not show only blue products, and click Execute. Highlight the code under the comment Step 7 - And re-execute the GetBlueProductsAndModels stored procedure, and click Execute. Highlight the code under the comment Step 8 - Query sys.procedures to see the list of procedures, and click Execute. Keep SQL Server Management Studio open for the next demo.
20
Lesson 3: Implementing Parameterized Stored Procedures
20762B Lesson 3: Implementing Parameterized Stored Procedures 9: Designing and Implementing Stored Procedures Parameter Sniffing and Performance Question What is the main advantage of creating parameterized stored procedures over nonparameterized stored procedures? Answer Parameterized stored procedures enable code reuse. One parameterized stored procedure can potentially replace many nonparameterized stored procedures.
21
Working with Parameterized Stored Procedures
20762B Working with Parameterized Stored Procedures 9: Designing and Implementing Stored Procedures Parameterized stored procedures contain three major components Input parameters Output parameters Return values
22
Using Input Parameters
20762B Using Input Parameters 9: Designing and Implementing Stored Procedures Parameters have prefix, a data type, and optionally a default value Parameters can be passed in order, or by name Parameters should be validated early in procedure code
23
Using Output Parameters
20762B Using Output Parameters 9: Designing and Implementing Stored Procedures OUTPUT must be specified When declaring the parameter When executing the stored procedure
24
Parameter Sniffing and Performance
20762B Parameter Sniffing and Performance 9: Designing and Implementing Stored Procedures Query plans generated for a stored procedure are generally reused the next time the stored procedure is executed In most cases this is desirable behavior Some stored procedures can benefit from different query plans for different sets of parameters Commonly called a “parameter sniffing” problem Options for resolving: WITH RECOMPILE in stored procedure code sp_recompile EXEC WITH RECOMPILE OPTION (OPTIMIZE FOR)
25
Lesson 4: Controlling Execution Context
20762B Lesson 4: Controlling Execution Context 9: Designing and Implementing Stored Procedures Demonstration: Viewing Execution Context Question What permission is needed to EXECUTE AS another login or user? ( )Option 1: sysadmin ( )Option 2: IMPERSONATE ( )Option 3: TAKE OWNERSHIP Answer (√) Option -2: IMPERSONATE
26
Controlling Executing Context
20762B Controlling Executing Context 9: Designing and Implementing Stored Procedures Security tokens Login token User token Control security context using EXECUTE AS
27
Enables impersonation Provides access to modules through impersonation
The EXECUTE AS Clause 9: Designing and Implementing Stored Procedures Enables impersonation Provides access to modules through impersonation Impersonate server-level principals or logins by using EXECUTE AS LOGIN Impersonate database-level principals or users by using EXECUTE AS USER
28
Viewing Execution Context
20762B Viewing Execution Context 9: Designing and Implementing Stored Procedures Details of the current security context can be viewed programmatically sys.login_token shows the login-related details sys.user_token shows all tokens that are associated with a user
29
Demonstration: Viewing Execution Context
20762B Demonstration: Viewing Execution Context 9: Designing and Implementing Stored Procedures In this demonstration, you will see how to: View and change the execution context Preparation Steps Ensure that the 20762B-MIA-DC and 20762B-MIA-SQL virtual machines are running and that you have completed the previous demonstrations in this module. Demonstration Steps In Solution Explorer, expand the Queries folder, and then double-click the 31 - Demonstration 3A.sql script file. Highlight the code under the comment Step 1 - Open a new query window to the tempdb database, and click Execute. Highlight the code under the comment Step 2 - Create a stored procedure that queries sys.login_token and sys.user_token, and click Execute. Highlight the code under the comment Step 3 - Execute the stored procedure and review the rowsets returned, and click Execute. Highlight the code under the comment Step 4 - Use the EXECUTE AS statement to change context, and click Execute. Highlight the code under the comment Step 5 - Try to execute the procedure. Why does it not it work? Click Execute and note the error message. Highlight the code under the comment Step 6 - Revert to the previous security context, and click Execute. Highlight the code under the comment Step 7 - Grant permission to SecureUser to execute the procedure, and click Execute. Highlight the code under the comment Step 8 - Now try again and note the output, and click Execute. Highlight the code under the comment Step 9 - Alter the procedure to execute as owner, and click Execute. Highlight the code under the comment Step 10 - Execute as SecureUser again and note the difference, and click Execute. (More notes on the next slide)
30
Lab: Designing and Implementing Stored Procedures
Exercise 3: Change Stored Procedure Execution Context Exercise 1: Create Stored Procedures In this exercise, you will create two stored procedures to support one of the new reports. Supporting Documentation Stored Procedure: Reports.GetProductColors Input Parameters: None Output Parameters: Output Columns: Color (from Marketing.Product) Notes: Colors should not be returned more than once in the output. NULL values should not be returned. Reports.GetProductsAndModels ProductID, ProductName, ProductNumber, SellStartDate, SellEndDate and Color (from Marketing.Product), ProductModelID (from Marketing.ProductModel), EnglishDescription, FrenchDescription, ChineseDescription. Output Order: ProductID, ProductModelID. For descriptions, return the Description column from the Marketing.ProductDescription table for the appropriate language. The LanguageID for English is “en”, for French is “fr” and for Chinese is “zh-cht”. If no specific language description is available, return the invariant language description if it is present. The LanguageID for the invariant language is a blank string ''. Where neither the specific language nor invariant language descriptions exist, return the ProductName instead. Logon Information Virtual machine: 20762B-MIA-SQL User name: ADVENTUREWORKS\Student Password: Pa$$w0rd Estimated Time: 45 minutes (More notes on the next slide)
31
20762B Lab Scenario 9: Designing and Implementing Stored Procedures 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.
32
20762B Lab Review 9: Designing and Implementing Stored Procedures In this lab, you learned how to create a stored procedure. You also learned how to change the execution context of a stored procedure and create a parameterized stored procedure.
33
Module Review and Takeaways
20762B Module Review and Takeaways 9: Designing and Implementing Stored Procedures Best Practice Best Practice: Include the SET NOCOUNT ON statement in your stored procedures immediately after the AS keyword. This improves performance. While it is not mandatory to enclose Transact-SQL statements within a BEGIN END block in a stored procedure, it is good practice and can help make stored procedures more readable. Reference objects in stored procedures using a two- or three-part naming convention. This reduces the processing that the database engine needs to perform. Avoid using SELECT * within a stored procedure even if you need all columns from a table. Specifying the column names explicitly reduces the chance of issues, should columns be added to a source table.
Similar presentations
© 2024 SlidePlayer.com. Inc.
All rights reserved.