Designing and Implementing Stored Procedures

Slides:



Advertisements
Similar presentations
Module 12: Auditing SQL Server Environments
Advertisements

Module 17 Tracing Access to SQL Server 2008 R2. Module Overview Capturing Activity using SQL Server Profiler Improving Performance with the Database Engine.
Week 6: Chapter 6 Agenda Automation of SQL Server tasks using: SQL Server Agent Scheduling Scripting Technologies.
Module 20 Troubleshooting Common SQL Server 2008 R2 Administrative Issues.
Chapter 7 Managing Data Sources. ASP.NET 2.0, Third Edition2.
Module 9 Designing an XML Strategy. Module 9: Designing an XML Strategy Designing XML Storage Designing a Data Conversion Strategy Designing an XML Query.
Database Security and Auditing: Protecting Data Integrity and Accessibility Chapter 3 Administration of Users.
Module 17 Storing XML Data in SQL Server® 2008 R2.
Overview What is SQL Server? Creating databases Administration Security Backup.
Database Security and Auditing: Protecting Data Integrity and Accessibility Chapter 3 Administration of Users.
Module 12 Handling Errors in T-SQL Code. Module Overview Understanding T-SQL Error Handling Implementing T-SQL Error Handling Implementing Structured.
Functions Lesson 10. Skills Matrix Function A function is a piece of code or routine that accepts parameters and stored as an object in SQL Server. The.
Module 19 Managing Multiple Servers. Module Overview Working with Multiple Servers Virtualizing SQL Server Deploying and Upgrading Data-Tier Applications.
Store Procedures Lesson 9. Skills Matrix Stored Procedures Stored procedures in SQL Server are similar to the procedures you write in other programming.
Module 8: Implementing Stored Procedures. Introducing Stored Procedures Creating, Modifying, Dropping, and Executing Stored Procedures Using Parameters.
Module 9 Designing and Implementing Stored Procedures.
Module 9 Authenticating and Authorizing Users. Module Overview Authenticating Connections to SQL Server Authorizing Logins to Access Databases Authorization.
Module 11: Programming Across Multiple Servers. Overview Introducing Distributed Queries Setting Up a Linked Server Environment Working with Linked Servers.
Module 14 Configuring Security for SQL Server Agent.
1 Chapter Overview Preparing to Upgrade Performing a Version Upgrade from Microsoft SQL Server 7.0 Performing an Online Database Upgrade from SQL Server.
Module 15 Monitoring SQL Server 2008 R2 with Alerts and Notifications.
Module 8: Implementing Stored Procedures. Overview Implementing Stored Procedures Creating Parameterized Stored Procedures Working With Execution Plans.
Module 4 Designing and Implementing Views. Module Overview Introduction to Views Creating and Managing Views Performance Considerations for Views.
Module 3 Designing and Implementing Tables. Module Overview Designing Tables Working with Schemas Creating and Altering Tables.
Permissions Lesson 13. Skills Matrix Security Modes Maintaining data integrity involves creating users, controlling their access and limiting their ability.
Module 11 Authorizing Users to Access Resources. Module Overview Authorizing User Access to Objects Authorizing Users to Execute Code Configuring Permissions.
Learningcomputer.com SQL Server 2008 –Views, Functions and Stored Procedures.
PRACTICE OVERVIEW PL/SQL Part Your stored procedure, GET_BUDGET, has a logic problem and must be modified. The script that contains the procedure.
Stored Procedures / Session 4/ 1 of 41 Session 4 Module 7: Introducing stored procedures Module 8: More about stored procedures.
Text TCS INTERNAL Oracle PL/SQL – Introduction. TCS INTERNAL PL SQL Introduction PLSQL means Procedural Language extension of SQL. PLSQL is a database.
Module 10 Merging Data and Passing Tables. Module Overview Using the MERGE Statement Implementing Table Types Using Table Types As Parameters.
Module 5: Managing Content. Overview Publishing Content Executing Reports Creating Cached Instances Creating Snapshots and Report History Creating Subscriptions.
SQL Triggers, Functions & Stored Procedures Programming Operations.
Data Integrity & Indexes / Session 1/ 1 of 37 Session 1 Module 1: Introduction to Data Integrity Module 2: Introduction to Indexes.
Project Management: Messages
Microsoft SQL Server 2014 for Oracle DBAs Module 8
Table spaces.
Working in the Forms Developer Environment
Data Virtualization Tutorial: Introduction to SQL Script
Using DML to Modify Data
Introduction to Microsoft SQL Server 2016
11 | Error Handling and Transactions
Sorting and Filtering Data
PROCEDURES, CONDITIONAL LOGIC, EXCEPTION HANDLING, TRIGGERS
Introduction to Triggers
UNIT - V STORED PROCEDURE.
Deploying and Configuring SSIS Packages
20761A 10: Using Subqueries Module 10   Using Subqueries.
Dynamic SQL Writing Efficient Queries on the Fly
20761A 11: Using Set Operators Module 11   Using Set Operators.
Automating SQL Server Management
Using Window Ranking, Offset, and Aggregate Functions
Module 5: Implementing Data Integrity by Using Constraints
20761B 12: Using Set Operators Module 12   Using Set Operators.
Module 13: Creating Data Visualizations with Power View
Transactions, Locking and Query Optimisation
Module 12: Implementing an Analysis Services Tabular Data Model
Using Table Expressions
Using JDeveloper.
Microsoft SQL Server 2014 for Oracle DBAs Module 7
Module 3: Supporting Self Service Reporting
Intermediate Security Topics in SQL SERver
Computer Science Projects Database Theory / Prototypes
Module 10: Implementing Managed Code in the Database
Contents Preface I Introduction Lesson Objectives I-2
A QUICK START TO OPL IBM ILOG OPL V6.3 > Starting Kit >
PRACTICE OVERVIEW PL/SQL Part - 1.
Using DML to Modify Data
Designing and Implementing User- Defined Functions
Responding to Data Manipulation Via Triggers
Presentation transcript:

Designing and Implementing Stored Procedures 20762B 9: Designing and Implementing Stored Procedures Module 9   Designing and Implementing Stored Procedures

Controlling Execution Context 20762B Module Overview 9: Designing and Implementing Stored Procedures Controlling Execution Context  

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.

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  

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  

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.

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.

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.

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 emailing 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.

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.

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.

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  

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  

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

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 @@TRANCOUNT 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  

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.

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 @@nestlevel 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  

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  

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.

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.  

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  

Using Input Parameters 20762B Using Input Parameters 9: Designing and Implementing Stored Procedures Parameters have the @ 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  

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  

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)  

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

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  

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  

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  

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)

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)

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.

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.  

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.