Module 8:Implementing Stored
Procedures
Introducing Stored Procedures
Creating, Modifying, Dropping, and ExecutingStored Procedures
Using Parameters in Stored Procedures
Handling Error Messages
Working with Stored Procedures
Overview
What Are Stored Procedures?
Advantages of Stored Procedures
Initial Processing of Stored Procedures
Subsequent Processing of Stored Procedures
Lesson: Introducing Stored Procedures
What Are Stored Procedures?
Named Collections of Transact-SQL Statements
Encapsulate Repetitive Tasks
Accept Input Parameters and Return OutputParameter Values
Return Status Value to Indicate Success or Failure
Five Types (System, Local, Temporary, Remote,and Extended)
Advantages of Stored Procedures
Share Application Logic
Shield Database Schema Details
Provide Security Mechanisms
Improve Performance
Reduce Network Traffic
Reduce Vulnerability to SQL Injection Attacks
Initial Processing of Stored Procedures
Entries into sysobjects and syscomments tablesEntries into sysobjects and syscomments tables
Compiled plan placed inprocedure cache Compiled plan placed inprocedure cache
Creation
Execution(first time or recompile) OptimizationOptimization
ParsingParsing
CompilationCompilation
Unused plan is aged outUnused plan is aged out
Execution Plan Execution Context
Connection 1
80828082
Connection 2
Connection 3
2424
10031003
Subsequent Processing of Stored Procedures
Execution Plan Retrieved
SELECT *FROM dbo.memberWHERE member_no = ?
Lesson: Creating, Modifying, Dropping, and Executing Stored Procedures
The CREATE PROCEDURE Statement
Guidelines for Creating Stored Procedures
The ALTER PROCEDURE Statement
The DROP PROCEDURE Statement
Stored Procedure Execution
The CREATE PROCEDURE Statement
Create in Current Database Using the CREATE PROCEDURE Statement
Can Nest to 32 Levels
Use sp_help to Display Information
USE NorthwindGOCREATE PROC dbo.OverdueOrdersAS SELECT * FROM dbo.Orders WHERE RequiredDate < GETDATE() AND ShippedDate IS NullGO
USE NorthwindGOCREATE PROC dbo.OverdueOrdersAS SELECT * FROM dbo.Orders WHERE RequiredDate < GETDATE() AND ShippedDate IS NullGO
dbo User Should Own All Objectsdbo User Should Own All Objects
Create, Test, and TroubleshootCreate, Test, and Troubleshoot
Avoid sp_ Prefix in Stored Procedure NamesAvoid sp_ Prefix in Stored Procedure NamesUse Same Connection Settings for AllStored ProceduresUse Same Connection Settings for AllStored Procedures
Minimize Use of Temporary Stored ProceduresMinimize Use of Temporary Stored Procedures
One Stored Procedure for One TaskOne Stored Procedure for One Task
Guidelines for Creating Stored Procedures
The ALTER PROCEDURE Statement
Altering Stored Procedures
Include any options in ALTER PROCEDURE Does not affect nested stored procedures
USE NorthwindGOALTER PROC dbo.OverdueOrdersASSELECT CONVERT(char(8), RequiredDate, 1) RequiredDate, CONVERT(char(8), OrderDate, 1) OrderDate, OrderID, CustomerID, EmployeeID FROM OrdersWHERE RequiredDate < GETDATE() AND ShippedDate IS NullORDER BY RequiredDateGO
USE NorthwindGOALTER PROC dbo.OverdueOrdersASSELECT CONVERT(char(8), RequiredDate, 1) RequiredDate, CONVERT(char(8), OrderDate, 1) OrderDate, OrderID, CustomerID, EmployeeID FROM OrdersWHERE RequiredDate < GETDATE() AND ShippedDate IS NullORDER BY RequiredDateGO
The DROP PROCEDURE Statement
Dropping Stored Procedures
Execute the sp_depends stored procedure to determine whether objects depend on the stored procedure
Procedure information is removed from the sysobjects and syscomments system tables
Required Permission
Procedure owner Members of db_owner, db_ddladmin, and sysadmin roles
USE NorthwindGODROP PROC dbo.OverdueOrdersGO
USE NorthwindGODROP PROC dbo.OverdueOrdersGO
Stored Procedure Execution
Executing a Stored Procedure by Itself
Executing a Stored Procedure Within anINSERT Statement
EXEC OverdueOrdersEXEC OverdueOrders
INSERT INTO CustomersEXEC EmployeeCustomerINSERT INTO CustomersEXEC EmployeeCustomer
Lab A: Creating Stored Procedures
Exercise 1: Writing and Executing a Stored Procedure
Exercise 2: Locating StoredProcedure Information
Lesson: Using Parameters in Stored Procedures
Input Parameters
Methods of Setting Parameter Values
Return Values Using OUTPUT Parameters
Return Values Using the RETURN Statement
Stored Procedure Recompile
Input Parameters
Validate All Incoming ParameterValues First
Provide Appropriate Default Values and IncludeNull Checks
CREATE PROCEDURE dbo.[Year to Year Sales] @BeginDate DateTime = Null, @EndDate DateTime = Null ASIF @BeginDate IS Null SET @BeginDate = dateadd(yy,-1,GetDate())
IF @EndDate IS Null SET @EndDate = GetDate()
IF Datediff(dd,@BeginDate,@EndDate) > 365 BEGIN RAISERROR('The maximum timespan allowed for this report is one year.', 14, 1) RETURN END
SELECT O.ShippedDate,O.OrderID,OS.Subtotal, DATENAME(yy,ShippedDate) AS YearFROM ORDERS O INNER JOIN [Order Subtotals] OS ON O.OrderID = OS.OrderIDWHERE O.ShippedDate BETWEEN @BeginDate AND @EndDate
GO
CREATE PROCEDURE dbo.[Year to Year Sales] @BeginDate DateTime = Null, @EndDate DateTime = Null ASIF @BeginDate IS Null SET @BeginDate = dateadd(yy,-1,GetDate())
IF @EndDate IS Null SET @EndDate = GetDate()
IF Datediff(dd,@BeginDate,@EndDate) > 365 BEGIN RAISERROR('The maximum timespan allowed for this report is one year.', 14, 1) RETURN END
SELECT O.ShippedDate,O.OrderID,OS.Subtotal, DATENAME(yy,ShippedDate) AS YearFROM ORDERS O INNER JOIN [Order Subtotals] OS ON O.OrderID = OS.OrderIDWHERE O.ShippedDate BETWEEN @BeginDate AND @EndDate
GO
Methods of Setting Parameter Values
Passing Values by Parameter Name
Passing Values by Position
EXEC AddCustomer 'ALFKI2', 'Alfreds Futterkiste', 'Maria Anders', 'Sales Representative', 'Obere Str. 57', 'Berlin', NULL, '12209', 'Germany', '030-0074321'
EXEC AddCustomer 'ALFKI2', 'Alfreds Futterkiste', 'Maria Anders', 'Sales Representative', 'Obere Str. 57', 'Berlin', NULL, '12209', 'Germany', '030-0074321'
EXEC AddCustomer @CustomerID = 'ALFKI', @ContactName = 'Maria Anders', @CompanyName = 'Alfreds Futterkiste', @ContactTitle = 'Sales Representative', @Address = 'Obere Str. 57', @City = 'Berlin', @PostalCode = '12209', @Country = 'Germany', @Phone = '030-0074321'
EXEC AddCustomer @CustomerID = 'ALFKI', @ContactName = 'Maria Anders', @CompanyName = 'Alfreds Futterkiste', @ContactTitle = 'Sales Representative', @Address = 'Obere Str. 57', @City = 'Berlin', @PostalCode = '12209', @Country = 'Germany', @Phone = '030-0074321'
CREATE PROCEDURE dbo.MathTutor @m1 smallint, @m2 smallint, @result int OUTPUTAS SET @result = @m1 * @m2GO
DECLARE @answer smallintEXECUTE MathTutor 5,6, @answer OUTPUTSELECT 'The result is: ', @answer
The result is: 30
CREATE PROCEDURE dbo.MathTutor @m1 smallint, @m2 smallint, @result int OUTPUTAS SET @result = @m1 * @m2GO
DECLARE @answer smallintEXECUTE MathTutor 5,6, @answer OUTPUTSELECT 'The result is: ', @answer
The result is: 30
Return Values Using OUTPUT Parameters
Results of StoredProcedure
Executing Stored
Procedure
Creating Stored
Procedure
CREATE PROC dbo.NewEmployee( @LastName nvarchar(20), @FirstName nvarchar(10) ) AS INSERT Employees(LastName,FirstName) VALUES (@LastName, @FirstName)
RETURN SCOPE_IDENTITY()Go
DECLARE @NewEmployeeId intEXEC @NewEmployeeId = dbo.NewEmployee @LastName='Hankin', @FirsName='Alex'
SELECT EmployeeID, LastName, FirstName FROM EmployeesWHERE EmployeeId = @NewEmployeeId
EmployeeID LastName FirstName ----------- -------------------- ---------- 10 Hankin Alex
CREATE PROC dbo.NewEmployee( @LastName nvarchar(20), @FirstName nvarchar(10) ) AS INSERT Employees(LastName,FirstName) VALUES (@LastName, @FirstName)
RETURN SCOPE_IDENTITY()Go
DECLARE @NewEmployeeId intEXEC @NewEmployeeId = dbo.NewEmployee @LastName='Hankin', @FirsName='Alex'
SELECT EmployeeID, LastName, FirstName FROM EmployeesWHERE EmployeeId = @NewEmployeeId
EmployeeID LastName FirstName ----------- -------------------- ---------- 10 Hankin Alex
Return Values Using the RETURN Statement
Result
Executing Stored
Procedure
Creating Stored
Procedure
Stored Procedure Recompile
Recompile When
Stored procedure returns widely varying result sets A new index is added to an underlying table The parameter value is atypical
Recompile by Using
CREATE PROCEDURE [WITH RECOMPILE] EXECUTE [WITH RECOMPILE] sp_recompile
Lesson: Handling Error Messages
Error Messages
Demonstration: Handling Error Messages
Error Messages
RETURN Statement Exits Query orProcedure Unconditionally
sp_addmessage Creates Custom Error Messages
@@error Contains Error Number for LastExecuted Statement
RAISERROR Statement
Returns user-defined or system error message Sets system flag to record error
Demonstration: Handling Error Messages
Handling error messages
Lesson: Working with Stored Procedures
Dynamic SQL in Stored Procedures
SQL Injection
Extended Stored Procedures
Performance Diagnosis Tools
Best Practices
Dynamic SQL in Stored Procedures
Dynamic Search Conditions
The IN Clause
Administrative Functions
SELECT @str = 'SELECT * FROM CUSTOMERS WHERE 1=1' IF LEN(@WhereCondition) > 0 SELECT @str = @str + @WhereCondition
EXEC sp_executesql @str
SELECT @str = 'SELECT * FROM CUSTOMERS WHERE 1=1' IF LEN(@WhereCondition) > 0 SELECT @str = @str + @WhereCondition
EXEC sp_executesql @str
SELECT @SQL = 'SELECT ProductID, ProductName, UnitPrice FROM Products WHERE ProductID IN (' + (@ProductIDs) + ')'
SELECT @SQL = 'SELECT ProductID, ProductName, UnitPrice FROM Products WHERE ProductID IN (' + (@ProductIDs) + ')'
SQL Injection
A Technique to Inject SQL Command as an Input
Caused by Passing User Input Directly to SQL Code
How to Avoid SQL Injection
Never trust user input Avoid dynamic SQL Execute with least privilege Store secrets securely Exceptions should divulge minimal information
Extended Stored Procedures
Characteristics of Extended Stored Procedures:
Programmed using open data services API Can include C and Microsoft Visual C++ features Can contain multiple functions Can be called from a client or SQL server Can be added to the master database only
EXEC master..xp_cmdshell 'dir c:\'EXEC master..xp_cmdshell 'dir c:\'
Performance Diagnosis Tools
Windows 2000 System Monitor
Object: SQL Server: Cache Manager Object: SQL Statistics
SQL Profiler
Can monitor events Can test each statement in a stored procedure
Design Each Stored Procedure to Accomplish a Single TaskDesign Each Stored Procedure to Accomplish a Single Task
Validate Data Before You Begin TransactionsValidate Data Before You Begin TransactionsUse the Same Connection Settings for AllStored ProceduresUse the Same Connection Settings for AllStored ProceduresUse WITH ENCRYPTION to Hide Text ofStored ProceduresUse WITH ENCRYPTION to Hide Text ofStored Procedures
Verify Input ParametersVerify Input Parameters
Best Practices
Lab B: Creating Stored Procedures Using Parameters
Exercise 1: Using the Create Stored Procedure Wizard
Exercise 2: Using Error Handling inStored Procedures
Exercise 3: Customizing Error Messages
Exercise 4: Using Return Codes
If Time Permits
Executing Extended Stored Procedures Tracing Stored Procedures Using
SQL Profiler