Module 8: Implementing Stored Procedures
Overview Implementing Stored Procedures Creating Parameterized Stored Procedures Working With Execution Plans Handling Errors
Lesson 1: Implementing Stored Procedures What Is a Stored Procedure? Syntax for Creating Stored Procedures Guidelines for Creating Stored Procedures Syntax for Altering and Dropping Stored Procedures
What Is a Stored Procedure? A named collection of Transact-SQL statements or Microsoft.NET Framework code Accepts input parameters and returns output parameter values Returns status value to indicate success or failure
Syntax for Creating Stored Procedures Create in current database by using the CREATE PROCEDURE statement Use EXECUTE to run stored procedure CREATE PROCEDURE Production.LongLeadProducts AS SELECTName, ProductNumber FROMProduction.Product WHEREDaysToManufacture >= 1 GO CREATE PROCEDURE Production.LongLeadProducts AS SELECTName, ProductNumber FROMProduction.Product WHEREDaysToManufacture >= 1 GO EXECUTE Production.LongLeadProducts
Qualify object names inside procedure Guidelines for Creating Stored Procedures Create one stored procedure for one task Create, test, and troubleshoot Avoid sp_ prefix in stored procedure names Use consistent connection settings for all stored procedures Minimize use of temporary stored procedures
Syntax for Altering and Dropping Stored Procedures ALTER PROCEDURE DROP PROCEDURE ALTER PROC Production.LongLeadProducts AS SELECTName, ProductNumber, DaysToManufacture FROMProduction.Product WHEREDaysToManufacture >= 1 ORDER BY DaysToManufacture DESC, Name GO ALTER PROC Production.LongLeadProducts AS SELECTName, ProductNumber, DaysToManufacture FROMProduction.Product WHEREDaysToManufacture >= 1 ORDER BY DaysToManufacture DESC, Name GO DROP PROC Production.LongLeadProducts
Lesson 2: Creating Parameterized Stored Procedures Input Parameters Output Parameters and Return Values Practice: Creating a Parameterized Stored Procedure
Input Parameters Provide appropriate default values Validate incoming parameter values, including null checks ALTER PROC int = 1 -- default value AS IF < 0) -- validate BEGIN RAISERROR('Invalid lead time.', 14, 1) RETURN END SELECTName, ProductNumber, DaysToManufacture FROMProduction.Product WHEREDaysToManufacture ORDER BY DaysToManufacture DESC, Name ALTER PROC int = 1 -- default value AS IF < 0) -- validate BEGIN RAISERROR('Invalid lead time.', 14, 1) RETURN END SELECTName, ProductNumber, DaysToManufacture FROMProduction.Product WHEREDaysToManufacture ORDER BY DaysToManufacture DESC, Name EXEC
CREATE PROC smallint OUTPUT AS INSERT INTO HumanResources.Department (Name, = SCOPE_IDENTITY() CREATE PROC smallint OUTPUT AS INSERT INTO HumanResources.Department (Name, = SCOPE_IDENTITY() int EXEC AddDepartment 'Refunds', OUTPUT int EXEC AddDepartment 'Refunds', OUTPUT Output Parameters and Return Values CREATE PROC smallint OUTPUT AS IF = '') OR = '')) RETURN -1 INSERT INTO HumanResources.Department (Name, = SCOPE_IDENTITY() RETURN 0 CREATE PROC smallint OUTPUT AS IF = '') OR = '')) RETURN -1 INSERT INTO HumanResources.Department (Name, = SCOPE_IDENTITY() RETURN 0 int = AddDepartment 'Refunds', OUTPUT IF = 0) ELSE SELECT 'Error during insert' int = AddDepartment 'Refunds', OUTPUT IF = 0) ELSE SELECT 'Error during insert'
Practice: Creating a Parameterized Stored Procedure In this practice, you will: Create a simple stored procedure Create a stored procedure that accepts an input parameter Create a stored procedure that accepts an output parameter and returns values Drop a stored procedure
Lesson 3: Working With Execution Plans What Is an Execution Plan? Viewing an Execution Plan Execution Plan Caching Query Compilation Forcing Stored Procedure Recompilation
Shows the actual or estimated execution of a query What Is an Execution Plan? Performance and Optimization Table or index scans Bookmark lookups Filter Sort Table or index scans Bookmark lookups Filter Sort
SQL Server Management Studio Open or type a Transact-SQL script Click Display Estimated Execution Plan or Include Actual Execution Plan button Query is parsed or executed Click the Execution plan tab Open or type a Transact-SQL script Click Display Estimated Execution Plan or Include Actual Execution Plan button Query is parsed or executed Click the Execution plan tab Viewing an Execution Plan Transact-SQL SET SHOWPLAN_XML ON SET SHOWPLAN_TEXT ON SET STATISTICS XML ON SET STATISTICS PROFILE ON
Execution Plan Caching Execution context connection 1 Execution context connection 1 Parameter value: 12 Execution context connection 2 Execution context connection 2 Parameter value: 24 Execution context connection 3 Execution context connection 3 Parameter value: 36 Query plan SELECT * FROM MyTable WHERE PriKey = ? SELECT * FROM MyTable WHERE PriKey = ? Procedure cache Age Cost
Query Compilation Parsing Normalization Compilation Optimization
Stored procedure recompilation sp_recompile WITH RECOMPILE at creation WITH RECOMPILE on execution sp_recompile WITH RECOMPILE at creation WITH RECOMPILE on execution Forcing Stored Procedure Recompilation USE AdventureWorks; GO EXEC sp_recompile N'Sales.Customer'; GO USE AdventureWorks; GO EXEC sp_recompile N'Sales.Customer'; GO
Lesson 4: Handling Errors Syntax for Structured Exception Handling Guidelines for Handling Errors Practice: Handling Errors
Syntax for Structured Exception Handling TRY…CATCH blocks provide the structure TRY block contains protected transactions CATCH block handles errors CREATE PROCEDURE int AS BEGIN TRY END TRY BEGIN CATCH END CATCH CREATE PROCEDURE int AS BEGIN TRY END TRY BEGIN CATCH END CATCH CREATE PROCEDURE int AS BEGIN TRY INSERT INTO TableWithKey END TRY BEGIN CATCH END CATCH CREATE PROCEDURE int AS BEGIN TRY INSERT INTO TableWithKey END TRY BEGIN CATCH END CATCH CREATE PROCEDURE int AS BEGIN TRY INSERT INTO TableWithKey END TRY BEGIN CATCH SELECT ERROR_NUMBER() ErrorNumber, ERROR_MESSAGE() [Message] END CATCH CREATE PROCEDURE int AS BEGIN TRY INSERT INTO TableWithKey END TRY BEGIN CATCH SELECT ERROR_NUMBER() ErrorNumber, ERROR_MESSAGE() [Message] END CATCH
BEGIN TRY -- INSERT INTO... END TRY SELECT * FROM TableWithKey -- NOT ALLOWED BEGIN CATCH -- SELECT ERROR_NUMBER() END CATCH BEGIN TRY -- INSERT INTO... END TRY SELECT * FROM TableWithKey -- NOT ALLOWED BEGIN CATCH -- SELECT ERROR_NUMBER() END CATCH BEGIN TRY BEGIN TRAN INSERT... COMMIT TRAN END TRY BEGIN CATCH ROLLBACK TRAN SELECT MESSAGE_NUMBER... END CATCH BEGIN TRY BEGIN TRAN INSERT... COMMIT TRAN END TRY BEGIN CATCH ROLLBACK TRAN SELECT MESSAGE_NUMBER... END CATCH SET XACT_ABORT ON BEGIN TRY BEGIN TRAN... COMMIT TRAN END TRY BEGIN CATCH IF (XACT_STATE()) = uncommitable ROLLBACK TRAN ELSE IF (XACT_STATE()) = 1-- commitable COMMIT TRAN END CATCH SET XACT_ABORT ON BEGIN TRY BEGIN TRAN... COMMIT TRAN END TRY BEGIN CATCH IF (XACT_STATE()) = uncommitable ROLLBACK TRAN ELSE IF (XACT_STATE()) = 1-- commitable COMMIT TRAN END CATCH BEGIN TRY... END TRY BEGIN CATCH INSERT INTO ErrorLog VALUES (ERROR_NUMBER(), ERROR_MESSAGE(), GETDATE()) END CATCH BEGIN TRY... END TRY BEGIN CATCH INSERT INTO ErrorLog VALUES (ERROR_NUMBER(), ERROR_MESSAGE(), GETDATE()) END CATCH Create CATCH block immediately after TRY Roll back failed transactions in CATCH Consider using XACT_ABORT ON and XACT_STATE Capture ERROR_xxx information if required Guidelines for Handling Errors Create CATCH block immediately after TRY Roll back failed transactions in CATCH Consider using XACT_ABORT ON and XACT_STATE Capture ERROR_xxx information if required
Practice: Handling Errors In this practice, you will add error handling to a stored procedure
Lab: Implementing Stored Procedures Exercise 1: Creating Stored Procedures Exercise 2: Working With Execution Plans