Download presentation
Presentation is loading. Please wait.
Published byMaude Carr Modified over 8 years ago
1
Module 8: Implementing Stored Procedures
2
Overview Implementing Stored Procedures Creating Parameterized Stored Procedures Working With Execution Plans Handling Errors
3
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
4
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
5
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
6
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
7
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
8
Lesson 2: Creating Parameterized Stored Procedures Input Parameters Output Parameters and Return Values Practice: Creating a Parameterized Stored Procedure
9
Input Parameters Provide appropriate default values Validate incoming parameter values, including null checks ALTER PROC Production.LongLeadProducts @MinimumLength int = 1 -- default value AS IF (@MinimumLength < 0) -- validate BEGIN RAISERROR('Invalid lead time.', 14, 1) RETURN END SELECTName, ProductNumber, DaysToManufacture FROMProduction.Product WHEREDaysToManufacture >= @MinimumLength ORDER BY DaysToManufacture DESC, Name ALTER PROC Production.LongLeadProducts @MinimumLength int = 1 -- default value AS IF (@MinimumLength < 0) -- validate BEGIN RAISERROR('Invalid lead time.', 14, 1) RETURN END SELECTName, ProductNumber, DaysToManufacture FROMProduction.Product WHEREDaysToManufacture >= @MinimumLength ORDER BY DaysToManufacture DESC, Name EXEC Production.LongLeadProducts @MinimumLength=4
10
CREATE PROC HumanResources.AddDepartment @Name nvarchar(50), @GroupName nvarchar(50), @DeptID smallint OUTPUT AS INSERT INTO HumanResources.Department (Name, GroupName) VALUES(@Name, @GroupName) SET @DeptID = SCOPE_IDENTITY() CREATE PROC HumanResources.AddDepartment @Name nvarchar(50), @GroupName nvarchar(50), @DeptID smallint OUTPUT AS INSERT INTO HumanResources.Department (Name, GroupName) VALUES(@Name, @GroupName) SET @DeptID = SCOPE_IDENTITY() DECLARE @dept int EXEC AddDepartment 'Refunds', '', @dept OUTPUT SELECT @dept DECLARE @dept int EXEC AddDepartment 'Refunds', '', @dept OUTPUT SELECT @dept Output Parameters and Return Values CREATE PROC HumanResources.AddDepartment @Name nvarchar(50), @GroupName nvarchar(50), @DeptID smallint OUTPUT AS IF ((@Name = '') OR (@GroupName = '')) RETURN -1 INSERT INTO HumanResources.Department (Name, GroupName) VALUES(@Name, @GroupName) SET @DeptID = SCOPE_IDENTITY() RETURN 0 CREATE PROC HumanResources.AddDepartment @Name nvarchar(50), @GroupName nvarchar(50), @DeptID smallint OUTPUT AS IF ((@Name = '') OR (@GroupName = '')) RETURN -1 INSERT INTO HumanResources.Department (Name, GroupName) VALUES(@Name, @GroupName) SET @DeptID = SCOPE_IDENTITY() RETURN 0 DECLARE @dept int, @result int EXEC @result = AddDepartment 'Refunds', '', @dept OUTPUT IF (@result = 0) SELECT @dept ELSE SELECT 'Error during insert' DECLARE @dept int, @result int EXEC @result = AddDepartment 'Refunds', '', @dept OUTPUT IF (@result = 0) SELECT @dept ELSE SELECT 'Error during insert'
11
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
12
Lesson 3: Working With Execution Plans What Is an Execution Plan? Viewing an Execution Plan Execution Plan Caching Query Compilation Forcing Stored Procedure Recompilation
13
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
14
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 1 1 3 3 4 4 2 2 Viewing an Execution Plan Transact-SQL SET SHOWPLAN_XML ON SET SHOWPLAN_TEXT ON SET STATISTICS XML ON SET STATISTICS PROFILE ON
15
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
16
Query Compilation Parsing Normalization Compilation Optimization
17
Stored procedure recompilation sp_recompile WITH RECOMPILE at creation WITH RECOMPILE on execution sp_recompile WITH RECOMPILE at creation WITH RECOMPILE on execution 1 1 3 3 2 2 Forcing Stored Procedure Recompilation USE AdventureWorks; GO EXEC sp_recompile N'Sales.Customer'; GO USE AdventureWorks; GO EXEC sp_recompile N'Sales.Customer'; GO
18
Lesson 4: Handling Errors Syntax for Structured Exception Handling Guidelines for Handling Errors Practice: Handling Errors
19
Syntax for Structured Exception Handling TRY…CATCH blocks provide the structure TRY block contains protected transactions CATCH block handles errors CREATE PROCEDURE dbo.AddData @a int, @b int AS BEGIN TRY END TRY BEGIN CATCH END CATCH CREATE PROCEDURE dbo.AddData @a int, @b int AS BEGIN TRY END TRY BEGIN CATCH END CATCH CREATE PROCEDURE dbo.AddData @a int, @b int AS BEGIN TRY INSERT INTO TableWithKey VALUES (@a, @b) END TRY BEGIN CATCH END CATCH CREATE PROCEDURE dbo.AddData @a int, @b int AS BEGIN TRY INSERT INTO TableWithKey VALUES (@a, @b) END TRY BEGIN CATCH END CATCH CREATE PROCEDURE dbo.AddData @a int, @b int AS BEGIN TRY INSERT INTO TableWithKey VALUES (@a, @b) END TRY BEGIN CATCH SELECT ERROR_NUMBER() ErrorNumber, ERROR_MESSAGE() [Message] END CATCH CREATE PROCEDURE dbo.AddData @a int, @b int AS BEGIN TRY INSERT INTO TableWithKey VALUES (@a, @b) END TRY BEGIN CATCH SELECT ERROR_NUMBER() ErrorNumber, ERROR_MESSAGE() [Message] END CATCH
20
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()) = -1 -- 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()) = -1 -- 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
21
Practice: Handling Errors In this practice, you will add error handling to a stored procedure
22
Lab: Implementing Stored Procedures Exercise 1: Creating Stored Procedures Exercise 2: Working With Execution Plans
Similar presentations
© 2025 SlidePlayer.com. Inc.
All rights reserved.