Documenti di Didattica
Documenti di Professioni
Documenti di Cultura
Stored Procedures
Compilation (Query processing and optimization will be thoroughly explained in the lecture)
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.
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).
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:
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'
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
To capture this result set, you need a place to store it. Temporary T-SQL Tables work well for
that:
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:
To run procedure:
Example:
CREATE PROC TestReturn (@InValue int)
AS
Return @Invalue
GO
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)
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
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 displayedmake the required modifications and save it
Exercises
Build a DB named “DB2Lab2”, then add a table named Inventory with the following schema:
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
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
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.
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