Stored Procedures
Stored Procedures
Database Programming
Stored Procedure
A stored procedure is a saved collection of Transact-
SQL statements
a batch that is stored in the database
or Precompiled script
2
Types of Stored Procedures
There are two types of stored procedures available in
SQL Server:
User defined stored procedures
System stored procedures
3
Stored Procedures – Advantages
Stored Procedures can be Easily Modified:
We can easily modify the code inside the stored procedure
without the need to re-deploy the application.
If the T-SQL queries were written in the application and if we
need to change the logic, we must change the code in the
application and re-deploy it.
SQL Server Stored procedures eliminate such challenges by
storing the code in the database.
so, when we want to change the logic inside the procedure we can just do it
by simple ALTER PROCEDURE statement.
4
Stored Proc – Advantages (cont.)
Reusable
Stored procedures can be executed by multiple users or multiple
client applications without the need of writing the code again.
Security
Stored procedures reduce the threat by eliminating direct access
to the tables.
(e.g.) Reduces risk of SQL Injection Attack
Performance:
When a stored procedure is executed for the first time, it creates
an execution plan which is saved in the buffer pool so that the
plan can be reused when it executes next time.
5
Stored Procedures vs Function
Functions must return a value (scalar or result set)
A Stored Procedure may or may not return any value.
Functions can have only input parameters
Procedures can have input or output parameters.
Functions can be called from a Stored Procedure
Stored Procedures cannot be called from a Function
A Stored Procedure allows ALL DML statement
Functions allows only statements that have NO side-effect
6
Stored Proc vs Function (cont.)
Procedures cannot be used in a select statement
Function can be embedded in a select statement.
Functions can be used in a
WHERE / HAVING / SELECT clauses
7
Check Points - Stored Procs
Why do we use Stored Procs?
Advantages of using Stored Procs?
Difference between Stored Procs and Used Defined
Functions?
System stored procedures vs User-Defined Stored Procs
NEXT
CREATE PROC Statement – Syntax
Parameters ( Input / Output )
Default
[ END ]
9
CREATE PROC Statement
Syntax Description
10
CREATE PROC Statement (cont.)
@parameter
11
@parameter (cont.)
The syntax is:
@parameter_name [AS] datatype [= default|NULL] [OUTPUT]
GO
13
Example
Create a stored procedure
CREATE PROCEDURE uspProductList
AS
BEGIN
SELECT productName, UnitPrice
FROM Product
ORDER BY productName
END
14
Using Named Parameters
Naming the parameters when executing the stored
procedure allows the parameters to be supplied in any
order
If you supply one parameter in the form of:
@parameter = value
Then, you must supply all subsequent parameters this way
15
Named Parameters - Example
CREATE my_proc @first int, @second int , @third int
AS
-- SQL statements
EXECUTE my_proc 1, 2, 3;
16
Default
If a default value is defined, the procedure can be
executed without specifying a value for that parameter
The default must be a constant or it can be NULL.
To make a parameter optional, you have to supply a
default value
CREATE PROCEDURE spGetEmployees
@DepID int = 1
AS
SELECT FirstName, LastName, JobTitle, Department
FROM Employee
WHERE DepID = @DepID
GO
EXECUTE spGetEmployees
EXECUTE spGetEmployees 2
17
Default Parameters - Example
CREATE PROCEDURE uspTestParameters2(
@param1 AS int
,@param2 AS int = NULL
,@param3 AS int = 0
)
AS
BEGIN
SELECT
'@param1 = ' + CAST(@param1 AS Varchar(10))
, '@param2 = ' + CAST(@param2 AS Varchar(10))
, '@param3 = ' + CAST(@param3 AS Varchar(10))
END
GO
exec uspTestParameters2 22
exec uspTestParameters2 22, 30
exec uspTestParameters2 22, DEFAULT, 30
exec uspTestParameters2 @param1 = 2, @param3 = 12
18
OUTPUT
OUTPUT parameters are used to return values to the
caller of the procedure
The keyword OUTPUT indicates that the parameter is an output
parameter
The value of this option can be returned to the calling
EXECUTE statement.
The OUTPUT keyword is required
In defining the parameter in the CREATE PROC statement
When the stored procedure is being called using the EXEC
statement
19
OUTPUT- Example
CREATE PROCEDURE uspGetSalary
@EmpID int
, @Salary money OUTPUT
AS
SELECT @Salary = Salary
FROM Employee
WHERE EmployeeID = @EmpID
GO
20
Executing Stored Procedures
When a procedure is executed for the first time, it is
compiled to determine an optimal access plan to retrieve
the data
Subsequent executions of the stored procedure may
reuse the plan already generated
EXEC or EXECUTE command is used
21
Returning Values from Procedures
Return Values are used:
To return data, such as an identity value or the
number of rows that the procedure has affected.
To return values to indicate the status of your stored
procedures
The recommended practice is to use return values to
indicate success or failure of the stored proc
By default, SQL Server automatically returns a value of
zero when your procedure is complete.
The RETURN value must be an integer
22
Return Values - Example
To pass a return value back from our proc to the calling code,
use the RETURN statement:
Example
CREATE PROCEDURE uspGetNames
@EmpID int
AS
SELECT Fname + ‘ ‘ + LName
FROM Employee
WHERE EmployeeID = @EmpID
Return @@RowCount
GO
23
Summary
Advantages of using Stored Procs?
Stored Procs Vs Used Defined Functions
System stored procedures vs User-Defined Stored Procs
CREATE PROC Statement
ALTER PROC
DROP PROC
24
Exercise
Write a stored procedure that inserts a new row into the
Student table and then adds one new record into the
Registration table
Student Registration
StudID Fname Lname RegID StudID CourseCode
25
Solution (partial)
Student Registration
StudID Fname Lname RegID StudID CourseCode
26
Exercise 2a
Create a stored procedure that returns the list names of
employees that work in a department, given the name of
the department.
EmpID Fname Lname DID DepID DepName
27
Exercise 2b
Update your stored procedure in the prev example so
that it returns the list names of employees that work in a
department and their number, given the name of the
department.
EmpID Fname Lname DID DepID DepName
28
Exercise 2 – Solution
CREATE PROCEDURE uspGetEmployeesByDep (
@depName varchar(50),
@employeeCount INT OUTPUT )
AS
BEGIN
SELECT FName , LName
FROM Employee E JOIN Department D ON E.DepID = D.DepID
WHERE D.DepName = @depName
Exercise: Update the above stored procedure so that it returns the list of employees
working in ALL departments when NO parameter is passed to it
29
ALTER Stored Procedures
ALTER PROC replaces the existing proc
The differences between using the ALTER PROC
statement and the CREATE PROC statement are:
ALTER PROC expects to find an existing proc
ALTER PROC retains any permissions that have been
established for the proc
ALTER PROC keeps the same object ID and allows the
dependencies to be kept
Dropping stored procedures
DROP PROC|PROCEDURE sproc_name
30
Calling Stored Procedures from C#
Using System.Data;
Using System.Data.SqlClient;
SqlDataReader dr = cmd.ExecuteReader(CommandBehavior.CloseConnection);
int returnValue = System.Int32.Parse(cmd.Parameters["@CityID"].Value.ToString());
return returnValue;
} 31