
Understanding Stored Procedures in SQL: A Complete Guide
Table of Content:
What is a Stored Procedure?
A stored procedure is a prepared SQL code that you can save, so the code can be reused over and over again.
So if you have an SQL query that you write over and over again, save it as a stored procedure, and then just call it to execute it.
You can also pass parameters to a stored procedure, so that the stored procedure can act based on the parameter value(s) that is passed.
A stored procedure is a precompiled set of one or more SQL statements that are stored on SQL Server. The benefit of Stored Procedures is that they are executed on the server-side and perform a set of actions, before returning the results to the client-side. This allows a set of actions to be executed with minimum time and also reduces the network traffic. Hence stored procedure improves performance to execute SQL statements.
Types of Stored Procedures
SQL Server divides the stored procedure into three major categories. Let us discuss each of them one by one:
- System-defined SPs: They are defined by the system and it starts with the prefix “sp” mostly. It can be used to complete a variety of SQL tasks.
- User-defined SPs: They are stored within a user database and created to perform a specific action. Here the prefix is different.
- Extended SPs: They are calling functions from DLL files. Developers don’t rely on these procedures. So, it is better to avoid them and focus on the other two.
Now We will discuss about User-defined stored procedure. Later We will discuss about System-defined SP and Extended SP.
Example: Use this below Database
Code:
USE TestDataBase
Code: Create a table to understand stored procedure
CREATE TABLE tbl_customer ( customerID INT PRIMARY KEY IDENTITY(100000000,1), customerSSNId INT, customerName VARCHAR(100), customerAge int, customerAddressLine1 VARCHAR(100), customerAddressLine2 VARCHAR(100), customerCityID VARCHAR(50), customerStateID VARCHAR(50) )
Code: Insert a record inside the table
INSERT INTO tbl_customer VALUES (12345678, 'Rumman Ansari', 23, 'Kolkata', 'Rajarhat', '12', '29')
Code: See the inserted record
Select * from tbl_customer
Example: Simple Store Procedure
Code: Create a store procedure which will select all custermer in the above table
/* Select All Customer Stored Procedure Example - 1 | Normal */ CREATE PROCEDURE SelectAllCustomers AS SELECT * FROM tbl_customer GO;
Code: Execute your above created stored procedure.
EXEC SelectAllCustomers;
- Question 1: What is a stored procedure?
- Question 2: What is a stored procedure?
- Question 3: Benefits of Stored Procedures