Você está na página 1de 9

2009/2010

Information Systems Department


Third Year IS and All Minor IS
Database 2
Lab2

Stored Procedures

What are stored procedures?


Stored procedures are collections of SQL statements and control-of-flow language. Stored
procedures differ from ordinary SQL statements and from batches of SQL statements in that they
are pre-compiled.

Compilation (Query processing and optimization will be thoroughly explained in the lecture)

A real life example of compilation


We are in FCI and need to go to “Ramsis Square” so we have many alternatives,
1. Walk to Dokki metro station and then take the metro:
a. Advantages are: cheap, no waiting time and it can be considered as fast
b. Disadvantages are: effort of walking
2. Wait for a bus that goes directly to Ramsis
a. Advantages are: cheap and no effort of walking
b. Disadvantages are: waiting time and the risk of getting stuck with the traffic jam
3. Take a taxi
a. Advantages are: no effort of walking, no waiting, and fast (the driver can take short
paths)
b. Disadvantages are: expensive
So the compilation here is to generate all plans and analyzing all the possible alternatives
then decide on the optimal plan  this what we eventually call “Query execution plan”

The first time you run a procedure, the query processor of the SQL server analyzes it and
prepares an execution plan that is ultimately stored in a system table. Any subsequent execution
of the procedure is according to the stored plan- so they execute very fast (as most of the work as
already been done)

Stored procedures accept data in the form of input parameters that are specified at execution
time. These input parameters are utilized in the execution of a series of statements that produce
some result. This result is returned to the calling environment (e.g. the application) through the
use of a record-set, output parameters and/or a return code.

Stored procedures in SQL Server are similar to procedures/functions in other programming


languages in that they can:

 Accept input parameters and return multiple values in the form of output parameters to the
calling procedure or batch.
 Contain programming statements that perform operations in the database, including calling
other procedures.
 Return a status value to a calling procedure or batch to indicate success or failure (and the
reason for the failure).

Benefits of stored procedures


 They allow modular programming/ efficient reuse of code: Stored Procedures are created
once and stored in the database, and can be called any number of times in the program.
Stored procedures can be created by a person who specializes in database programming, and
they can be modified independently of the program source code. (An example could be: if we
have a database that is used by many applications, by using stored procedures we will save
the time of writing the same SQL statements in each application and thus saving the time of
compiling each one of them separately, also make a consistent use of the database. So all
what you have to do is calling the stored procedures from your code)
 Precompiled: SQL Server compiles each stored procedure once and then reutilizes
the execution plan. This results in tremendous performance boosts when stored procedures
are called repeatedly. They are parsed and optimized when they are first executed, and a
compiled version of the stored procedure remains in memory cache for later use. This means
the stored procedure does not need to be reparsed and re-optimized with each use resulting in
much faster execution times.
 Reduce network traffic: An operation requiring hundreds of lines of Transact-
SQL code can be performed through a single statement that executes the code in a procedure,
rather than by sending hundreds of lines of code over the network.
 Security Mechanism: Users can be granted permission to execute a stored
procedure even if they do not have permission to execute the procedure's statements directly.
This point can be postponed till they take the Security topic, or we can say it in a general
way)
 Can run on local or remote server: You can execute a stored procedure on either a
local or remote SQL Server. (We can make global database on the server with all stored
procedures which can be used by any other local database)
 Hide Database Details: Stored procedures can shield users from needing to know
the details of the tables in the database. If a set of stored procedures supports all of the
business functions users need to perform, users never need to access the tables directly; they
can just execute the stored procedures that model the business processes with which they are
familiar.

Stored procedures syntax


In the query analyzer:

Creating a procedure:
CREATE PROCEDURE <Procedure_Name> <@Param1>
<Datatype_For_Param1=<Default_Value_For_Param1>,
<@Param2><Datatype_For_Param2> = <Default_Value_For_Param2>,…
AS
SQL and Control flow statements for procedure
GO
Executing a procedure:

Exec procedure_name <paramaters values>


Example:
CREATE PROCEDURE all_employees
AS
SELECT * FROM employees
GO
To run the procedure:
EXEC all_employees

Using Parameters with stored procedures:


 One or more parameters are allowed
 Parameters as named storage locations (as variables in conventional programming
languages)
 Parameter names are preceded by @
 Parameter names are local to the procedure in which they're defined.

Example:
CREATE PROCEDURE sp_addEmployee (@E_name char(15), @E_dept char(20))
AS
INSERT INTO employees VALUES (@E_name, @E_dept)
GO
EXEC sp_addEmployee 'Ahmed Hassan', 'IS'

Example with default values for parameters:

CREATE PROCEDURE spGetAddress @City nvarchar(30) = NULL, @AddressLine1


nvarchar(60) = NULL
AS
SELECT *
FROM AdventureWorks.Person.Address
WHERE City = @City
AND AddressLine1 = @AddressLine1
GO

Updating/Modifying a procedure:
Alter procedure procedure_name Parameters
As
--Modified Procedure Statments
Go
Example:
ALTER PROCEDURE uspGetAddress @City nvarchar(30)
AS
SELECT *
FROM AdventureWorks.Person.Address
WHERE City LIKE @City + '%'
GO
Delete/Drop a procedure:
DROP PROCEDURE procedure_name

Returning a value from a stored procedure

Stored procedure can return:


 A result set for each SELECT statement contained in the stored procedure or any other
stored procedures called by the stored procedure.
CREATE PROCEDURE dbo.GetPeopleByLastName (@LastName NVARCHAR(50))
AS
SELECT ContactID,
FirstName,
LastName
FROM Person.Contact
WHERE LastName = @LastName
ORDER BY ContactID

EXEC dbo.GetPeopleByLastName @LastName = 'Alexander'

To capture this result set, you need a place to store it.  Temporary T-SQL Tables work well for
that:

DECLARE @People TABLE (


ContactID INT,
FirstName NVARCHAR(50),
LastName NVARCHAR(50)
)

INSERT @People (ContactID, FirstName, LastName) EXEC


dbo.GetPeopleByLastName @LastName = 'Alexander'
SELECT COUNT(*) FROM @People
GO

 Using Output parameter, which can return either data (such as an integer or character
value) or a cursor variable (cursors are result sets that can be retrieved one row at a time).

Example:

CREATE PROCEDURE uspGetAddressCount @City nvarchar(30),@AddressCount int


OUTPUT
AS
SELECT @AddressCount = count(*)
FROM AdventureWorks.Person.Address
WHERE City = @City

To run procedure:

Declare @count int


Exec uspGetAddressCount ‘cairo’, @count output

 Use Return value, which must be an integer value

Example:
CREATE PROC TestReturn (@InValue int)
AS
Return @Invalue
GO

declare @retval int


exec @retval = TestReturn 3
select retval= @retval

Example of procedure that fills an output parameter and also returns value:
CREATE PROCEDURE EMPLOYEE_SALARY (@EMP_name VarChar(15), @Salary VarChar(5)
OUTPUT) AS
-- Declare variables
DECLARE @sal Int
SELECT @Salary = emp_salary
FROM Employee
WHERE Emp_Name = @EMP_name
IF @@RowCount > 0
BEGIN
SELECT @sal = 1
RETURN @sal
END
ELSE
BEGIN
SELECT @sal = 0
RETURN @sal
END
GO

Example for returning a cursor (which enables retrieval of many rows together):
Use AdventureWorks
CREATE PROCEDURE RetrieveRecord (@reorderpoint int, @ret_cur CURSOR VARYING
OUTPUT)
AS
DECLARE cur1 CURSOR FOR
select ProductId, name from production.product where Reorderpoint =
@reorderpoint
OPEN cur1
SET @ret_cur = cur1
GO

Declare @e cursor
Declare @reorderpoint int
Declare @productID int
Declare @name varchar(50)

set @reorderpoint = 750

exec RetrieveRecord @reorderpoint, @e output

fetch next from @e into @productId, @name


while @@fetch_status = 0
begin
fetch next from @e into @productId, @name
print cast(@productId as varchar(50)) +'--' + @name
end
close @e
deallocate cur1
deallocate @e
Notes:

 Don’t forget to select the required DB from the DDL at the top in the Query Analyzer screen
 Stored procedures are treated like all other objects in the database. They are therefore subject to all
of the same naming conventions and other limitations. For example, the name of a stored procedure
cannot contain spaces and it can’t be a reserved word and can't start with number.

There is another way to create stored procedures that enables you to edit in them:
In SQL 2005:
1. Open the SQL Management Studio, from databases node  “your database”
Programmability Stored Procedures and right click then “New Stored Procedure”
2. A window will be opened, write the code of your stored procedure in it (of course
without the “EXEC” part) and save it
3. The SP that you just created will appear with the other system defined SPs
4. If you want to edit it, double click on its name, edit it, and then press “OK”
5. If you want to run the SP, go to the Query Analyzer and type the “EXEC SPname”
command

To delete/Modify a procedure from enterprise manager:

1. Open the SQL Server Enterprise Manager, from databases node  “your database”
Programmability Stored Procedures
2. Right click on the required SP
3. Press “Delete” Or If you want to modify it press “Modify”, A window with the description
of the SP will be displayedmake the required modifications and save it
Exercises

Build a DB named “DB2Lab2”, then add a table named Inventory with the following schema:

ID Product Warehouse Quantity


1 Apple Giza 100
2 Banana Cairo 200
3 Corn Cairo 150
4 Watermelon Giza 20
5 Carrot Giza 50
1. Create a stored procedure that retrieves all the products with their quantities for a
certain warehouse.
Answer:
CREATE PROCEDURE sp_GetInventory @location varchar(10)
AS
SELECT Product, Quantity
FROM Inventory
WHERE Warehouse = @location
Go

2. Create another SP which has an integer input parameter. This SP should retrieve the
number of products that satisfy the following condition: product quantity is less than the
value of the input parameter (use output parameter / return value)
Answer:
CREATE PROCEDURE sp_BelowThreshold @Pro_Threshold int, @count int output
AS
SELECT @count = count(*)(ID)
FROM Inventory
WHERE Quantity < @Pro_Threshold
Go

CREATE PROCEDURE sp_BelowThreshold @Pro_Threshold int


AS
Declare @count int
SELECT @count =count(*)(ID)
FROM Inventory
WHERE Quantity < @Pro_Threshold
Return @count
Go

3. Create another a table Employees (EID int, Ename varchar(30), Salary float)
EID Ename Salary
1 Ahmed 1000
2 Ali 1200
3 Hany 300
Create a SP which has an integer input parameter. This SP should increase the salaries of
all the employees till the average salary is greater than or equal the input value
Answer:
CREATE PROCEDURE sp_IncreaseSalary @Salary_increment int
AS
WHILE (SELECT avg(salary) from Employees) < @Salary_increment
BEGIN
UPDATE Employees SET Salary = Salary + 10
END

Stored Procedure Example (Not to be explained in the lab)

This simple stored procedure example illustrates three ways stored procedures can return data:

1. It first issues a SELECT statement that returns a result set summarizing the order activity
for the stores in the sales table.

2. It then issues a SELECT statement that fills an output parameter.

3. Finally, it has a RETURN statement with a SELECT statement that returns an integer.
Return codes are generally used to pass back error checking information. This procedure
runs without errors, so it returns another value to illustrate how returned codes are filled.

USE Northwind
GO
DROP PROCEDURE OrderSummary
GO
CREATE PROCEDURE OrderSummary @MaxQuantity INT OUTPUT AS
-- SELECT to return a result set summarizing
-- employee sales.
SELECT Ord.EmployeeID, SummSales = SUM(OrDet.UnitPrice * OrDet.Quantity)
FROM Orders AS Ord
JOIN [Order Details] AS OrDet ON (Ord.OrderID = OrDet.OrderID)
GROUP BY Ord.EmployeeID
ORDER BY Ord.EmployeeID

-- SELECT to fill the output parameter with the


-- maximum quantity from Order Details.
SELECT @MaxQuantity = MAX(Quantity) FROM [Order Details]

-- Return the number of all items ordered.


RETURN (SELECT SUM(Quantity) FROM [Order Details])
GO

-- Test the stored procedure.

-- DECLARE variables to hold the return code


-- and output parameter.
DECLARE @OrderSum INT
DECLARE @LargestOrder INT

-- Execute the procedure, which returns


-- the result set from the first SELECT.
EXEC @OrderSum = OrderSummary @MaxQuantity = @LargestOrder OUTPUT

-- Use the return code and output parameter.


PRINT 'The size of the largest single order was: ' +
CONVERT(CHAR(6), @LargestOrder)
PRINT 'The sum of the quantities ordered was: ' +
CONVERT(CHAR(6), @OrderSum)
GO

Você também pode gostar