Module 9 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.
Module 6 Implementing Table Structures in SQL Server ®2008 R2.
Module 10: Implementing User-defined Functions. Overview What Is a User-defined Function? Defining Examples.
Module 9: Implementing Stored Procedures. Introduction to Stored Procedures Creating Executing Modifying Dropping Using Parameters in Stored Procedures.
Module 9 Designing an XML Strategy. Module 9: Designing an XML Strategy Designing XML Storage Designing a Data Conversion Strategy Designing an XML Query.
Module 13 Automating SQL Server 2008 R2 Management.
Module 17 Storing XML Data in SQL Server® 2008 R2.
Module 18 Monitoring SQL Server 2008 R2. Module Overview Monitoring Activity Capturing and Managing Performance Data Analyzing Collected Performance Data.
SQL Basics. SQL SQL (Structured Query Language) is a special-purpose programming language designed from managing data in relational database management.
Introduction to SQL 2005 Security Nick Ward SQL Server Specialist Nick Ward SQL Server Specialist
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.
Stored Procedures A stored procedure is a named collection of SQL statements language. You can create stored procedures for commonly used functions and.
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.
Defining Stored Procedures Named Collections of Transact-SQL Statements Encapsulate Repetitive Tasks Five Types (System, Local, Temporary, Remote, and.
Dexterity | CONFIDENTIAL 2009 MRO | Analytics | Insights 1 Stored Procedures.
Module 7 Reading SQL Server® 2008 R2 Execution Plans.
Security David Frommer Principal Architect Business Intelligence Microsoft Partner of the Year 2005 & 2007.
Module 8: Implementing Stored Procedures. Introducing Stored Procedures Creating, Modifying, Dropping, and Executing Stored Procedures Using Parameters.
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.
Module 10 Assigning Server and Database Roles. Module Overview Working with Server Roles Working with Fixed Database Roles Creating User-defined Database.
Module 15 Monitoring SQL Server 2008 R2 with Alerts and Notifications.
Module 18 Querying XML Data in SQL Server® 2008 R2.
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.
Slide 1 of 19Session 13 Ver. 1.0 Querying and Managing Data Using SQL Server 2005 In this session, you will learn to: Implement stored procedures Implement.
Session 1 Module 1: Introduction to Data Integrity
SQL Server 2012 Session: 1 Session: 12 Triggers Data Management Using Microsoft SQL Server.
Module 3: Using XML. Overview Retrieving XML by Using FOR XML Shredding XML by Using OPENXML Introducing XQuery Using the xml Data Type.
Stored Procedures / Session 4/ 1 of 41 Session 4 Module 7: Introducing stored procedures Module 8: More about stored procedures.
Ch 5. Introducing More Database Objects. Database Objects Table (ch2) View (ch3) Stored Procedure Trigger Function User-defined types.
Module 10 Merging Data and Passing Tables. Module Overview Using the MERGE Statement Implementing Table Types Using Table Types As Parameters.
Module 9: Using Advanced Techniques. Considerations for Querying Data Working with Data Types Cursors and Set-Based Queries Dynamic SQL Maintaining Query.
Module 5: Managing Content. Overview Publishing Content Executing Reports Creating Cached Instances Creating Snapshots and Report History Creating Subscriptions.
Module 8: Using Programming Objects for Data Retrieval.
Module 6: Modifying Data in Tables. Inserting Data into Tables Deleting Data from Tables Updating Data in Tables Overview of Transactions.
SQL Triggers, Functions & Stored Procedures Programming Operations.
Create Stored Procedures and Functions Database Management Fundamentals LESSON 2.4.
SQL Basics Review Reviewing what we’ve learned so far…….
Dynamic SQL Writing Efficient Queries on the Fly ED POLLACK AUTOTASK CORPORATION DATABASE OPTIMIZATION ENGINEER.
Module 9: Implementing Functions. Overview Creating and Using Functions Working with Functions Controlling Execution Context.
Module 9: Implementing User-Defined Functions. Overview Introducing User-Defined Functions Implementing User-Defined Functions.
Views / Session 3/ 1 of 40 Session 3 Module 5: Implementing Views Module 6: Managing Views.
Module 5: Working with Subqueries. Writing Basic Subqueries Writing Correlated Subqueries Comparing Subqueries with Joins and Temporary Tables Using Common.
Data Integrity & Indexes / Session 1/ 1 of 37 Session 1 Module 1: Introduction to Data Integrity Module 2: Introduction to Indexes.
More SQL: Complex Queries, Triggers, Views, and Schema Modification
Trigger used in PosgreSQL
Parameter Sniffing in SQL Server Stored Procedures
Dynamic SQL Writing Efficient Queries on the Fly
Stored Procedures – Facts and Myths
Dynamic SQL: Writing Efficient Queries on the Fly
Module 7: Implementing Views
Dynamic SQL Writing Efficient Queries on the Fly
Module 5: Implementing Data Integrity by Using Constraints
Overview Implementing Triggers Implementing XML Schemas.
Dynamic SQL: Writing Efficient Queries on the Fly
Using Table Expressions
More SQL: Complex Queries, Triggers, Views, and Schema Modification
Module 10: Implementing Managed Code in the Database
Contents Preface I Introduction Lesson Objectives I-2
මොඩියුල විශ්ලේෂණය Stored Procedure හඳුන්වා දීම.
Designing and Implementing User- Defined Functions
Designing and Implementing Stored Procedures
Presentation transcript:

Module 9 Designing and Implementing Stored Procedures

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

Using Input Parameters CREATE PROCEDURE tinyint = 5 AS SELECT soh.SalesOrderID,soh.OrderDate,soh.CustomerID FROM Sales.SalesOrderHeader AS soh WHERE soh.DueDate AND soh.[Status] ORDER BY soh.SalesOrderID; GO EXEC Sales.OrdersByDueDateAndStatus ' ',5; EXEC Sales.OrdersByDueDateAndStatus ' '; EXEC = = 5; CREATE PROCEDURE tinyint = 5 AS SELECT soh.SalesOrderID,soh.OrderDate,soh.CustomerID FROM Sales.SalesOrderHeader AS soh WHERE soh.DueDate AND soh.[Status] ORDER BY soh.SalesOrderID; GO EXEC Sales.OrdersByDueDateAndStatus ' ',5; EXEC Sales.OrdersByDueDateAndStatus ' '; EXEC = = 5; Parameters  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

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

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)

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

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

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 int OUTPUT AS = COUNT(1) FROM Sales.SalesOrderHeader AS soh WHERE soh.DueDate CREATE PROC int OUTPUT AS = COUNT(1) FROM Sales.SalesOrderHeader AS soh WHERE soh.DueDate CREATE PROC int OUTPUT WITH EXECUTE AS 'Pat' AS = COUNT(1) FROM Sales.SalesOrderHeader AS soh WHERE soh.DueDate CREATE PROC int OUTPUT WITH EXECUTE AS 'Pat' AS = COUNT(1) FROM Sales.SalesOrderHeader AS soh WHERE soh.DueDate

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 …

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

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

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

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.

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

Module Review and Takeaways Review Questions Best Practices