Download as pptx, pdf, or txt
Download as pptx, pdf, or txt
You are on page 1of 48

Data Management Using

Microsoft SQL Server


Database Administration &
Management
Session: 1 (IT-3142)
Session: 1 RDBMS Concepts
Lecture # 12-13
Introduction to the Web
SQL
Server
2012
Lecture # 12-13 Agenda:
At the end of the lecture, students will be able to understand:
● What are Stored Procedures
● Features of Stored Procedures
● Types of Stored Procedures
● Syntax of Stored Procedures
● Creating Stored Procedures using SSMS & T-SQL
● Executing Stored Procedures
● Modifying Stored Procedures using SSMS & T-SQL
● Dropping Stored Procedures using SSMS & T-SQL
● Input & output parameters in Stored Procedures
● Disadvantages of Stored Procedures

© Aptech Ltd.
SQL
Server
2012
Stored Procedures

• A stored procedure is a group of one or more pre-compiled SQL statements


into a logical unit.
• It is stored as an object inside the database server.
• It is a subroutine or a subprogram in the common computing language that has
been created and stored in the database.
• Each procedure in SQL Server always contains a name, parameter lists, and
Transact-SQL statements.
• The SQL Database Server stores the stored procedures as named objects.
• We can invoke the procedures by using triggers, other procedures, and
applications such as Java, Python, PHP, etc.
• It can support almost all relational database systems.
• SQL Server builds an execution plan when the stored procedure is called the
first time and stores them in the cache memory.
• The plan is reused by SQL Server in subsequent executions of the stored
procedure, allowing it to run quickly and efficiently.
• Stored procedures are useful when repetitive tasks have to be performed.
• Stored procedures can accept values in the form of input parameters and
return output values as defined by the output parameters.
© Aptech Ltd.
SQL
Server
2012
Stored Procedures (cont.)
• The figure below represents the stored procedures in SQL.

© 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

User-Defined Stored Procedures

User-defined stored procedures are also known as custom 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.

Transact-SQL stored procedures consist of Transact-SQL statements whereas the CLR


stored procedures are based on the .NET framework CLR methods.

Both the stored procedures can take and return user-defined parameters.

© Aptech Ltd.
SQL
Server
2012
System Stored Procedures

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.

System stored procedures allow GRANT, DENY, and REVOKE permissions.

A system stored procedure is a set of pre-compiled Transact-SQL statements


executed as a single unit.

System procedures are used in database administrative and informational activities.

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

Catalog Stored Procedures


• All information about tables in the user database is stored in a set of
tables called the system catalog.
• Information from the system catalog can be accessed using catalog
procedures.
• For example, the sp_tables catalog stored procedure displays the
list of all the tables in the current database.

Security Stored Procedures


• Security stored procedures are used to manage the security of the
database.
• For example, the sp_changedbowner security stored procedure is
used to change the owner of the current database.

Cursor Stored Procedures


• Cursor procedures are used to implement the functionality of a
cursor.
• For example, the sp_cursor_list cursor stored procedure lists all
the cursors opened by the connection and describes their attributes.
© Aptech Ltd.
SQL
Classification of System Stored Procedures (cont.)
Server
2012

Distributed Query Stored Procedures


• Distributed stored procedures are used in the management of
distributed queries.
• For example, the sp_indexes distributed query stored procedure
returns index information for the specified remote table.

Database Mail and SQL Mail Stored Procedures


• Database Mail and SQL Mail stored procedures are used to perform
e-mail operations from within the SQL Server.
• For example, the sp_send_dbmail database mail stored
procedure sends e-mail messages to specified recipients.
• The message may include a query resultset or file attachments or
both.

© Aptech Ltd.
SQL
Server
2012
Stored Procedure Syntax

We can create a stored procedure in SQL Server in two ways:

1. Using T-SQL Query


2. Using SQL Server Management Studio

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

• In this syntax, the AS keyword distinguishes the stored procedure's heading and


body.
• The BEGIN and END keywords that accompany a single statement in a stored
procedure are optional.
• However, it's a good idea to include them to make the code more understandable.
© Aptech Ltd.
SQL
Server
2012
SQL Server Stored Procedures Example
The following is an example to create stored procedures in SQL Server using T-
SQL:

© 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?

We can use the EXEC command to call/execute stored procedures in SQL


Server. The following syntax illustrates the execution of 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.)

The following is an example to execute stored procedures in SQL Server:

© 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:

1. Using T-SQL Query


2. Using SQL Server Management Studio

© 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:

• Run the procedure to check whether we have successfully updated


the procedure or not.

© 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 ALTER PROCEDURE statement alters a single procedure.


When a stored procedure calls other stored procedures, the nested stored
procedures are not affected by altering the calling procedure.

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  

• Let us understand how to use Output Parameters in a stored procedure


with the help of an example.
• The following statement will create a procedure called sp_count_records,
in which we will declare an integer type variable called @Count and use
the OUTPUT keyword.
• The procedure uses the COUNT function to find the number of records in
the table, and then the value is assigned to the output parameter.

© 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 parameter cannot be of text and image data type.

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

• We can create temporary procedures in the same way as we can create


temporary tables.
• The tempdb database is used to create these procedures.
• We can divide the temporary procedures into two types:

1. Local Temporary Stored Procedures


2. Global Temporary Procedures.

1. Local Temporary Stored Procedures:


• We can create this type of procedure by using the # as prefix and accessed
only in the session in which they were created.
• When the connection is closed, this process is immediately terminated.
• Here's an example of how to create a local temporary procedure:

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.

⮚ The syntax used to execute an extended stored procedure is as follows:

Syntax:

EXECUTE <procedure_name>

⮚ Following code snippet executes the extended stored procedure xp_fileexist to check
whether the MyTest.txt file exists or not.

EXECUTE xp_fileexist 'c:\MyTest.txt’

© Aptech Ltd.
SQL
Server
2012
Nested Stored Procedures

SQL Server 2012 enables stored procedures to be called inside other stored
procedures.

The called procedures can in turn call other procedures.

This architecture of calling one procedure from another procedure is referred to as


nested stored procedure architecture.

The maximum level of nesting supported by SQL Server 2012 is 32.

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.)

⮚ Following code snippet is used to create a stored procedure NestedProcedure that


calls two other stored procedures that were created earlier.

CREATE PROCEDURE NestedProcedure


AS
BEGIN
EXEC uspGetCustTerritory
EXEC uspGetSales 'France'
END

⮚ When the procedure NestedProcedure is executed, this procedure in turn invokes


the uspGetCustTerritory and uspGetSales stored procedures and passes the
value France as the input parameter to the uspGetSales stored procedure.

© 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.

EXEC sp_helptext sp_insert_data

© Aptech Ltd.
SQL
Server
How to list all stored procedures in SQL Server?
2012

• When we have several procedures, it is very important to list all


procedures. Because sometimes the procedure names are the same in
many databases.
• In that case, this query is very useful. We can list all stored procedure in
the current database as follows:

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:

• Debugging: Since debugging stored procedures is never simple, it is not


advised to write and execute complex business logic using them. As a
result, if we will not handle it properly, it can result in a failure.

• Dependency: As we know, professional DBAs and database developers


handle vast data sets in large organizations. And the application developers
must depend on them because any minor changes must be referred to a
DBA, who can fix bugs in existing procedures or build new ones.

• Expensive: Stored procedures are costly to manage in terms of DBAs


because organizations would have to pay extra costs for specialist DBAs. A
DBA is much more qualified to handle complex database procedures.

• Specific to a Vendor: Stored procedures written in one platform cannot


run on another. Since procedures written in Oracle are more complicated,
we will need to rewrite the entire procedure for SQL Server.
© Aptech Ltd.
SQL
Server
2012Stored Procedures vs Functions

© Aptech Ltd.

You might also like