Data Management Using Microsoft SQL Server: Database Administration & Management (IT-3142) Lecture # 12-13
Data Management Using Microsoft SQL Server: Database Administration & Management (IT-3142) Lecture # 12-13
Data Management Using Microsoft SQL Server: Database Administration & Management (IT-3142) Lecture # 12-13
© Aptech Ltd.
SQL
Server
2012
Stored Procedures
© Aptech Ltd.
SQL
Server
2012
Features of Stored Procedures in SQL Server
The following are the features of stored procedure in SQL Server:
1. Reduced Traffic:
• A stored procedure reduces network traffic between the application and
the database server, resulting in increased performance.
• It is because instead of sending several SQL statements, the application
only needs to send the name of the stored procedure and its parameters.
2. Stronger Security:
• The procedure is always secure because it manages which processes and
activities we can perform.
• It removes the need for permissions to be granted at the database object
level and simplifies the security layers.
3. Reusable:
• Stored procedures are reusable.
• It reduces code inconsistency, prevents unnecessary rewrites of the same
code, and makes the code transparent to all applications or users.
© Aptech Ltd.
SQL
Server
2012
Features of Stored Procedures in SQL Server (cont.)
4. Easy Maintenance:
• The procedures are easier to maintain without restarting or deploying the
application.
5. Improved Performance:
• Stored Procedure increases the application performance.
• Once we create the stored procedures and compile them the first time, it
creates an execution plan reused for subsequent executions.
• The procedure is usually processed quicker because the query processor
does not have to create a new plan.
© Aptech Ltd.
SQL
Server
2012
Main Types of Stored Procedures
SQL Server categorizes the stored procedures mainly in two types:
1. User-defined Stored Procedures
2. System Stored Procedures
© Aptech Ltd.
SQL
Server
2012
User-Defined Stored Procedures
These procedures are used for reusing Transact-SQL statements for performing
repetitive tasks.
There are two types of user-defined stored procedures, the Transact-SQL stored
procedures and the Common Language Runtime (CLR) stored procedures.
Both the stored procedures can take and return user-defined parameters.
© Aptech Ltd.
SQL
Server
2012
System Stored Procedures
System stored procedures are commonly used for interacting with system tables
and performing administrative tasks such as updating system tables.
The system stored procedures are prefixed with 'sp_'. These procedures are located
in the Resource database.
These procedures can be seen in the sys schema of every system and user-defined
database.
When referencing a system stored procedure, the sys schema identifier is used.
System stored procedures are owned by the database administrator.
© Aptech Ltd.
SQL
Server
2012
Classification of System Stored Procedures
© Aptech Ltd.
SQL
Server
2012
Stored Procedure Syntax
The following are the basic syntax to create stored procedures in SQL Server:
CREATE PROCEDURE [schema_name].procedure_name
@parameter_name data_type,
....
parameter_name data_type
AS
BEGIN
-- SQL statements
-- SELECT, INSERT, UPDATE, or DELETE statement
END
© Aptech Ltd.
SQL
Server
2012
Parameter Explanations
The stored procedure syntax has the following parameters:
1. Schema_name: It is the name of your database or schema. By default, a
procedure is associated with the current database, but we can also
create it into another database by specifying the DB name.
2. Procedure_Name: It represents the name of your stored procedure that
should be meaningful names so that you can identify them quickly. It
cannot be the system reserved keywords.
3. Parameter_Name: It represents the number of parameters. It may be
zero or more based upon the user requirements. We must ensure that
we used the appropriate data type.
For example, @Name VARCHAR(25).
SET NOCOUNT ON in Stored Procedure:
• In some cases, we use the SET NOCOUNT ON statement in the stored
procedure.
• This statement prevents the message that displays the number of rows
affected by SQL queries from being shown.
• NOCOUNT denotes that the count is turned off.
• It means that if SET NOCOUNT ON is set, no message would appear
indicating the number of rows affected.
© Aptech Ltd.
SQL
Server
2012
How to execute/call a stored procedure?
EXEC procedure_name;
Or,
EXECUTE procedure_name;
If we are using the SSMS, we need to use the below steps to execute stored
procedures:
1. Navigate to the Programmability -> Stored Procedures.
2. Next, select the Stored Procedure menu and expand it. You will see the
available stored procedures.
3. Right-click on the stored procedure you want to execute and choose
the Execute Stored Procedure.
4. The Execute Procedure window will appear. If the procedure has any
parameters, we must assign/pass them before clicking OK to execute it. If
no parameters are defined, click OK to run the procedure.
© Aptech Ltd.
SQL
Server
2012
How to execute/call a stored procedure? (cont.)
© Aptech Ltd.
SQL
Server
2012
Stored Procedure Using SSMS
If we are using the SSMS, use the following steps for creating the stored
procedure:
Step 1: Select the Database -> Programmability -> Stored Procedures.
© Aptech Ltd.
SQL
Server
2012
Stored Procedure Using SSMS (cont.)
Step 2: Right-click on the Stored Procedures folder to open the menu and
then select the New -> Stored Procedure option as follows:
© Aptech Ltd.
SQL
Server
2012
Stored Procedure Using SSMS (cont.)
Step 3: When we select the New Stored Procedure option, we will get the new
query window containing the default Stored Procedure Template. Here, we can add
the procedure name, parameters (if any), and the SQL query we want to use.
© Aptech Ltd.
SQL
Server
2012How to modify stored procedures in SQL Server?
We need to update or modify the stored procedure over a period of time. SQL
Server allows us to update or modify an existing stored procedure in two
ways:
© Aptech Ltd.
SQL
Server
2012Modify Stored Procedures using SSMS
The following steps help to learn how we can modify or make changes in
stored procedures:
Step 1: Navigate to the Database -> Programmability -> Stored Procedures.
Step 2: Expand the Stored Procedures folder, right-click on the stored
procedure that you want to modify, and then select the Modify option as
follows:
© Aptech Ltd.
SQL
Server
2012Modify Stored Procedures using SSMS (cont.)
Step 3: Once we click the Modify option, we will get a new query window
with an auto-generated ALTER PROCEDURE code. Here we can make changes
as per our needs.
© Aptech Ltd.
SQL
Server
2012Modify Stored Procedures using T-SQL Query
• SQL Server provides an ALTER PROCEDURE statement to make
modifications in the existing stored procedures.
• If we want to modify the above created stored procedure, we can write
the ALTER PROCEDURE statement as follows:
© Aptech Ltd.
SQL
Server
2012Modify Stored Procedures using T-SQL Query (cont.)
• Using the EXECUTE statement, we will get the below output where we can
see that our stored procedure is successfully modified.
© Aptech Ltd.
SQL
Guidelines for Using ALTER PROCEDURE
Server
2012
Statement
When a stored procedure is created using options such as the WITH ENCRYPTION
option, these options should also be included in the ALTER PROCEDURE
statement.
The creators of the stored procedure, members of the sysadmin server role and
members of the db_owner and db_ddladmin fixed database roles have the
permission to execute the ALTER PROCEDURE statement.
It is recommended that you do not modify system stored procedures. If you need to
change the functionality of a system stored procedure, then create a user-defined
system stored procedure by copying the statements from an existing stored
procedure and modify this user-defined procedure.
© Aptech Ltd.
SQL
Server
2012How to delete/drop stored procedures in SQL Server?
We can delete the stored procedure in SQL Server permanently. SQL Server
removes the stored procedure in two ways:
1. Using T-SQL Query
2. Using SQL Server Management Studio
© Aptech Ltd.
SQL
Server
2012DROP Stored Procedures using SSMS
The following steps help to learn how we can delete stored procedures:
Step 1: Go to the Database -> Programmability -> Stored Procedures.
Step 2: Expand the Stored Procedures folder, right-click on the stored
procedure that you want to remove, and then select the Delete option as
follows:
© Aptech Ltd.
SQL
Server
2012DROP Stored Procedures using SSMS (cont.)
Step 3: Once we click the Delete option, we will get a Delete Object window.
We can check the dependencies by clicking on the Show Dependencies
button and then click OK to remove the stored procedure.
© Aptech Ltd.
SQL
Server
2012Delete Stored Procedures using T-SQL Query
• SQL Server provides a DROP PROCEDURE statement to remove the existing
stored procedures.
• We can write the DROP PROCEDURE statement as follows:
DROP PROCEDURE procedure_name;
© Aptech Ltd.
SQL
Server
2012
Using Parameters
The real advantage of a stored procedure comes into picture only when one or more
parameters are used with it.
Data is passed between the stored procedure and the calling program when a call is
made to a stored procedure.
⮚ This data transfer is done using parameters. Parameters are of two types that are as
follows:
Input • Input parameters allow the calling program to pass values to a stored procedure.
Parameters • These values are accepted into variables defined in the stored procedure.
• Output parameters allow a stored procedure to pass values back to the calling
Output program.
Parameters
• These values are accepted into variables by the calling program.
© Aptech Ltd.
SQL
Server
2012Input Parameters in Stored Procedure
• SQL Server allows us to create input parameters stored procedures.
• This type of stored procedure can enable us to pass one or more parameters to
get the filtered result.
• If we want to execute this stored procedure, we need to pass the value for
the @Id parameter.
© Aptech Ltd.
SQL
Server
2012Output Parameters in Stored Procedure
• SQL Server enables us to provide many output parameters in a stored
procedure.
• These output parameters can be of any valid data type, such as integer,
date, or character.
• We can use the below syntax to create an output parameter in the stored
procedure:
parameter_name data_type OUTPUT
© Aptech Ltd.
SQL
Server
2012Output Parameters in Stored Procedure (cont.)
CREATE PROCEDURE sp_count_records
@Count INT OUTPUT
AS
BEGIN
SELECT @Count = COUNT(Id) FROM tbl_data;
END
Now, we will execute the stored procedure. Here, we need to pass the output
parameter @Count as follows:
Declare an Int Variable that corresponds to the Output parameter in SP
DECLARE @Total INT
Don't forget to use the keyword OUTPUT
EXEC sp_count_records @Total OUTPUT
Print the result
PRINT @Total
© Aptech Ltd.
SQL
Server
2012Output Parameters in Stored Procedure (cont.)
© Aptech Ltd.
SQL
Server
2012Output Parameters in Stored Procedure (cont.)
⮚ OUTPUT parameters have the following characteristics:
The calling statement must contain a variable to receive the return value.
The variable can be used in subsequent Transact-SQL statements in the batch or the
calling procedure.
⮚ The OUTPUT clause returns information from each row on which the INSERT,
UPDATE, and DELETE statements have been executed.
⮚ This clause is useful to retrieve the value of an identity or computed column after an
INSERT or UPDATE operation.
© Aptech Ltd.
SQL
Server
2012Other types of Stored Procedure
Following are the other types of stored procedures:
• Temporary
• Remote
• Extended
• Nested
© Aptech Ltd.
SQL
Server
Temporary Stored Procedure
2012
CREATE PROCEDURE #Temp
AS
BEGIN
PRINT 'Local temp procedure'
END
© Aptech Ltd.
SQL
Server
2012Temporary Stored Procedure (cont.)
2. Global Temporary Stored Procedure:
• We can create this type of procedure by using the ## as a prefix and accessed
from any sessions.
• When the connection that was used to create the procedure is closed, this
procedure is automatically terminated.
• Here's an example of how to create a global temporary procedure:
CREATE PROCEDURE ##TEMP
AS
BEGIN
PRINT 'Global temp procedure'
END
© Aptech Ltd.
SQL
Local Temporary Procedure vs Global Temporary
Server
2012
Procedure
© Aptech Ltd.
SQL
Server
2012
Remote Stored Procedures
Stored procedures that run on remote SQL Servers are known as remote stored
procedures.
Remote stored procedures can be used only when the remote server allows remote
access.
When a remote stored procedure is executed from a local instance of SQL Server to
a client computer, a statement abort error might be encountered.
When such an error occurs, the statement that caused the error is terminated but
the remote procedure continues to be executed.
© Aptech Ltd.
SQL
Server
2012
Extended Stored Procedures
Extended stored procedures are used to perform tasks that are unable to be
performed using standard Transact-SQL statements.
Extended stored procedures use the 'xp_' prefix. These stored procedures are
contained in the dbo schema of the master database.
Syntax:
EXECUTE <procedure_name>
⮚ Following code snippet executes the extended stored procedure xp_fileexist to check
whether the MyTest.txt file exists or not.
© Aptech Ltd.
SQL
Server
2012
Nested Stored Procedures
SQL Server 2012 enables stored procedures to be called inside other stored
procedures.
If a stored procedure attempts to access more than 64 databases, or more than two
databases in the nesting architecture, there will be an error.
© Aptech Ltd.
SQL
Server
2012
Nested Stored Procedures (cont.)
© Aptech Ltd.
SQL
Server
2012
@@NESTLEVEL Function (cont.)
⮚ The level of nesting of the current procedure can be determined using the
@@NESTLEVEL function.
⮚ When the @@NESTLEVEL function is executed within a Transact-SQL string, the
value returned is the current nesting level + 1.
⮚ If you use sp_executesql to execute the @@NESTLEVEL function, the value
returned is the current nesting level + 2 (as another stored procedure, namely
sp_executesql, gets added to the nesting chain).
Syntax:
@@NESTLEVEL
where,
@@NESTLEVEL: Is a function that returns an integer value specifying the level of
nesting.
© Aptech Ltd.
SQL
Server
2012
Viewing Stored Procedure Definitions
⮚ The definition of a stored procedure can be viewed using the sp_helptext system
stored procedure.
⮚ To view the definition, you must specify the name of the stored procedure as the
parameter when executing sp_helptext.
⮚ This definition is in the form of Transact-SQL statements.
⮚ The Transact-SQL statements of the procedure definition include the CREATE
PROCEDURE statement as well as the SQL statements that define the body of the
procedure.
⮚ The syntax used to view the definition of a stored procedure is as follows:
Syntax:
sp_helptext '<procedure_name>‘
⮚ Following code snippet displays the definition of the stored procedure named
sp_insert_data.
© Aptech Ltd.
SQL
Server
How to list all stored procedures in SQL Server?
2012
SELECT * FROM sys.procedures;
The best way for listing all user-defined stored procedures in a database is to
use the ROUTINES information schema view as below:
SELECT ROUTINE_SCHEMA, ROUTINE_NAME
FROM INFORMATION_SCHEMA.ROUTINES
WHERE ROUTINE_TYPE = 'PROCEDURE’;
OR
SELECT * FROM db_name.INFORMATION_SCHEMA.ROUTINES
WHERE ROUTINE_TYPE = 'PROCEDURE’
© Aptech Ltd.
SQL
Server
2012Disadvantages of Stored Procedures
The following are the limitations of stored procedures in SQL Server:
© Aptech Ltd.