You are on page 1of 22

Implementing Stored

Procedures
Overview

Introducing Stored Procedures


Creating, Modifying, Dropping, and Executing
Stored Procedures
Using Parameters in Stored Procedures
Handling Error Messages
Working with Stored Procedures
Lesson: Introducing Stored Procedures

What Are Stored Procedures?


Advantages of Stored Procedures
Initial Processing of Stored Procedures
Subsequent Processing of Stored Procedures
What Are Stored Procedures?

Named Collections of Transact-SQL Statements


Encapsulate Repetitive Tasks
Accept Input Parameters and Return Output
Parameter Values
Advantages of Stored Procedures

Share Application Logic


Provide Security Mechanisms
Improve Performance
Reduce Network Traffic
Reduce Vulnerability to SQL Injection Attacks
Initial Processing of Stored Procedures

Creation
Entries into sysobjects
Parsing
and syscomments tables

Execution
(first time or Optimization
recompile)

Compiled plan placed in


Compilation
procedure cache
Subsequent Processing of Stored Procedures

Execution Plan Retrieved


Execution Plan Execution Context

8082
Connection 1
SELECT *
FROM
dbo.member 24
WHERE Connection 2
member_no = ?
1003
Connection 3

Unused plan is aged out


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

create proc usp_orderdetails


as
select orderid, sum(quantity)
from [order details]
group by orderid

Can Nest to 32 Levels


Use sp_help to Display Information
The ALTER PROCEDURE Statement

Altering Stored Procedures


 Include any options in ALTER PROCEDURE
 Does not affect nested stored procedures

alter proc usp_orderdetails


as
select productid, orderid, sum(quantity)
from [order details]
group by productid, orderid
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

drop proc usp_orderdetails


Lab A: Creating Stored Procedures

Exercise 1: Writing and Executing a


Stored Procedure
Exercise 2: Locating Stored
Procedure 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 create proc usp_insertemp(@empname


Incoming varchar(50), @salary int)
Parameter as
Values First
insert emp values (@empname, @salary)
Provide return ident_current ('emp')
Appropriate
Default Values
and Include
Null Checks
Methods of Setting Parameter Values

Passing Values by Parameter Name

declare @x int -- for return


exec@x= usp_insertemp @empname='gehad', @salary=1000
-- here the order is not important
print @x

Passing Values by Position

declare @x int -- for return


exec@x= usp_insertemp 'sara',2000
-- here the order is important
Return Values Using OUTPUT Parameters

create proc usp_manipulation (@first int, @second int,


@sum int output)
Creating Stored as
Procedure set @sum = @first + @second
declare @multi int
set @multi = @first * @second
return @multi

declare @x int -- for output


Executing Stored declare @y int -- for return
Procedure exec @y = usp_manipulation 10,20, @x output -- notice
ther is no brackets
print @x
print @y
Results of Stored
Procedure The result is: @x=30
@y=200
create proc usp_cat (@catid int, @catname varchar(50) output,
@productsno int output)
as
select @catname = categoryname, @productsno
Creating Stored =count(productid)
from categories join products
Procedure on categories.categoryid = products.categoryid
where categories.categoryid = @catid
group by categoryname

declare @x varchar(50)
Executing Stored declare @y int
exec usp_cat 1,@x output,@y output
Procedure print @x
print @y

Beverages
Result 12
Stored Procedure Recompile

Recompile When
 Stored procedure returns widely varying result sets
 A new index is added to an underlying table

Recompile by Using
 CREATE PROCEDURE [WITH RECOMPILE] after the
parameters.
 EXECUTE [WITH RECOMPILE]
 sp_recompile
Lab

■Create a scalar user-defined function named GetMaximumDiscountForCategory


within the Sales schema that retrieves the maximum discount percentage
currently available for a specific category. Create an @Category varchar(50)
parameter to limit the results based on the category, and use the GETDATE
function to limit the rows based on whether the discount is currently available
(using Sales.SpecialOffer).

■ Create an inline table-valued user-defined function named GetDiscountsForDate


within the Sales schema that retrieves the discounts. The function accepts an
@DateToCheck datetime parameter to filter the discounts based on the
provided date. This allows Adventure Works to test what discounts will be
available on a specific date.
■ Create a multi-statement table-valued user-defined function
named GetDiscountedProducts within the Sales schema that
uses a complex query to retrieve products that have a
discount. This complex query will be provided to you. The
function accepts an @IncludeHistory bit parameter to filter the
returned table based on whether the discount history
information is required or only the current information is
needed. The returned table will include the following
definition.(using Sales.SpecialOfferProduct, Sales.SpecialOffer, Production.Product)
ProductID int,Name nvarchar(50)
ListPrice money,DiscountDescription nvarchar(255)
DiscountPercentage smallmoney,DiscountAmount money
DiscountedPrice money
■ Create a stored procedure named GetDiscounts within the Sales schema that
retrieves the following columns from Sales.SpecialOffer:
Description,DiscountPct, Type, Category, StartDate, EndDate, MinQty, and
MaxQty. The procedure should return all rows sorted by StartDate and
EndDate(using Sales.SpecialOffer)
.
■ Create a stored procedure named GetDiscountsForCategory within the Sales
schema that accepts an input parameter named @Category, which is an varchar
data type accepting up to 50 characters. The procedure should retrieve the same
columns as for GetDiscounts but should filter the rows based on the @Category
parameter.

■ Create a stored procedure named GetDiscountsForCategoryAndDate within the


Sales schema that accepts the @Category parameter as for
GetDiscountsForCategory but includes an additional @DateToCheck
datetimeinput parameter.The @DateToCheck parameter must be able to accept
a NULL default value. If a NULL value is specified for the @DateToCheck
parameter, set the parameter value to the current date and time by using the
GETDATE function.The procedure should retrieve the same columns as for
GetDiscounts but should filter the rows based on the @Category and
@DateToCheck parameters.
Create a stored procedure named AddDiscount within the Sales schema that inserts
new records into the Sales.SpecialOffer table. The following table specifies the
required parameters for the insert.
Parameter name Data type (input unless otherwise specified)
@Description nvarchar(255)
@DiscountPct smallmoney
@Type nvarchar(50)
@Category nvarchar(50)
@StartDate datetime
@EndDate datetime
@MinQty int
@MaxQty int
@NewProductID int OUTPUT
If the new insert succeeds, the@NewProductID parameter must be updated with the
SCOPE_IDENTITY function value.

You might also like