0% found this document useful (0 votes)
47 views31 pages

Stored Procedures

Uploaded by

Subscribe 001
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
47 views31 pages

Stored Procedures

Uploaded by

Subscribe 001
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 31

Stored Procedure

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

 A stored procedure is a prepared SQL code that you can


save, so that the code can be reused again.

 Mainly used to hide direct SQL execution from


application code and improve performance of database
operations

2
Types of Stored Procedures
 There are two types of stored procedures available in
SQL Server:
 User defined stored procedures
 System stored procedures

 User defined stored procedures


 User defined stored procedures are created by database
developers or database administrators.
 These stored procedures contains one or more SQL statements
to select, update, or delete records from database tables
 System stored procedures
 These are built-in stored procedures that are mostly used for
administrative purposes.

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.

 Reduce Network Traffic:


 When we use stored procedures, only the call to execute the
procedure is passed over the network
 Instead of the every single line of code.

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

 Functions that return tables can be used in the FROM


clause of a SELECT statement (as a data source)
 This can be used in JOINs with other tables
 Stored Procedures cannot be used in the FROM clause

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

 Stored Procs Return Values


 Executing Stored procedure
8
Creating a Stored Procedure
 Syntax

CREATE { PROC | PROCEDURE } procedure_name


[ @parameterdata_type } [OUTPUT ] ] [ ,...n ]
AS
[ BEGIN ]
sql_statement [ ,...n ]

[ END ]

9
CREATE PROC Statement
Syntax Description

 CREATE PROCEDURE or PROC can be used


 The name of the stored procedure is an identifier name
 Parameters are optional
 The actual code is written after the AS keyword
 Optionally BEGIN … END can be used for statement
blocks

10
CREATE PROC Statement (cont.)
@parameter

 One or more parameters can be declared in a CREATE


PROCEDURE statement
 The value of each declared parameter must be supplied
by the user when the procedure is called
 unless a default for the parameter is defined
 Declaring a parameter requires the following info:
 The name
 The data type
 The default value
 The direction (input or output)

11
@parameter (cont.)
 The syntax is:
@parameter_name [AS] datatype [= default|NULL] [OUTPUT]

 The name of the parameter must start with the @ sign


 The data type must be declared
 If you don’t supply a default value, then
 the parameter is assumed to be required, and
 a value must be supplied when the stored procedure is called

 Values can be passed to stored procedures


 by explicitly naming the parameters and assigning the
appropriate value or
 by supplying the parameter values given in the CREATE
PROCEDURE statement without naming them
12
CREATE PROC Statement (cont.)
Data Type: Each parameter must have a data type

CREATE PROCEDURE uspGetEmployee


@EmpID INT
AS
SELECT FirstName, LastName, JobTitle, Department
FROM EmployeeDepartment
WHERE EmployeeID = @ EmpID

GO

13
Example
 Create a stored procedure
CREATE PROCEDURE uspProductList
AS
BEGIN
SELECT productName, UnitPrice
FROM Product
ORDER BY productName
END

 Execute the stored procedure


EXEC uspProductList

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

 If you do not supply parameters in the form


@parameter = value
 Then, you must supply them in the order given in the CREATE
PROCEDURE statement.

15
Named Parameters - Example
CREATE my_proc @first int, @second int , @third int
AS
-- SQL statements

 my_proc expects three parameters


 @first, @second, and @third

 My_proc can be called in one of the following ways

EXECUTE my_proc @second = 2, @first = 1, @third = 3;

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 @param1 = 22


exec uspTestParameters2 22

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

DECLARE @retVal money


EXEC uspGetSalary 5, @retVal OUTPUT
select @retVal

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

 Nested Stored Procedure


 Nested Stored procedures refers to one stored procedure can
call another

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

DECLARE @Return int;

EXEC @Return = uspGetNames 22;


SELECT @Return;

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

 Different parts of a Stored Procedure


 Parameters ( Input / Output )
 Named Parameters
 Optional Parameters
 Return statement
 Executing Stored procedure

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

DECLARE @identyVal int

INSERT Student ( Fname, LName)


VALUES (‘Genet', ‘Abebe')

SET @identyVal = SCOPE_IDENTITY()

INSERT Registration ( StudID, CourseCode)


VALUES (@identyVal, ‘CS333’)l

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

SET @employeeCount = @@ROWCOUNT


END
GO

DECLARE @empCount INT


EXEC uspGetEmployeesByDep 'Sales', @empCount OUTPUT
SELECT @empCount AS 'Number of employees found’

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;

public static int InsertCity(string dbConStr, CityObj newCityObj)


{
SqlConnection cnn = new SqlConnection();
cnn = DatabaseManager.openAdminConnection(dbConStr);
SqlCommand cmd = null;

cmd = new SqlCommand();


cmd.Connection = cnn;
cmd.CommandType = System.Data.CommandType.StoredProcedure;
cmd.CommandText = "spCityInsert";

SqlParameter outParam = new SqlParameter();


outParam = cmd.Parameters.Add("@CityID", SqlDbType.Int);
outParam.Direction = ParameterDirection.Output;

cmd.Parameters.Add("@CityName", SqlDbType.NVarChar, 50).Value = newCityObj.CityName;


cmd.Parameters.Add("@IsActive", SqlDbType.Bit).Value = newCityObj.IsActive;

SqlDataReader dr = cmd.ExecuteReader(CommandBehavior.CloseConnection);
int returnValue = System.Int32.Parse(cmd.Parameters["@CityID"].Value.ToString());

return returnValue;
} 31

You might also like