The Wayback Machine - https://web.archive.org/web/20240930181002/https://www.geeksforgeeks.org/what-is-stored-procedures-in-sql/
Open In App

SQL Stored Procedures

Last Updated : 08 May, 2024
Summarize
Comments
Improve
Suggest changes
Like Article
Like
Save
Share
Report
News Follow

A stored procedure in SQL is a group of SQL queries that can be saved and reused multiple times. It is very useful as it reduces the need for rewriting SQL queries. It enhances efficiency, reusability, and security in database management.

Users can also pass parameters to stored procedures so that the stored procedure can act on the passed parameter values.

Stored Procedures are created to perform one or more DML operations on the Database. It is nothing but a group of SQL statements that accepts some input in the form of parameters, performs some task, and may or may not return a value. 

Syntax

Two important syntaxes for using stored procedures in SQL are:

Syntax to Create a Stored Procedure 

CREATE PROCEDURE procedure_name
(parameter1 data_type, parameter2 data_type, …)
AS
BEGIN
   — SQL statements to be executed
END

Syntax to Execute the Stored Procedure

EXEC procedure_name parameter1_value, parameter2_value, ..

Parameter

The most important part is the parameters. Parameters are used to pass values to the Procedure. There are different types of parameters, which are as follows: 

  1. BEGIN: This is what directly executes or we can say that it is an executable part.
  2. END: Up to this, the code will get executed.

SQL Stored Procedure Example

Let’s look at an example of Stored Procedure in SQL to understand it better.

Imagine a database named “SampleDB”, a table named “Customers” with some sample data, and a stored procedure named” GetCustomersByCountry”.

The stored procedure takes the parameter “Country” and returns a list of customers from the “Customers” table that matches the specified country. Finally, the stored procedure is executed with the parameter “Sri Lanka” to retrieve the list of customers from Sri Lanka.

Query:

-- Create a new database named "SampleDB"
CREATE DATABASE SampleDB;

-- Switch to the new database
USE SampleDB;

-- Create a new table named "Customers"
CREATE TABLE Customers (
CustomerID INT PRIMARY KEY,
CustomerName VARCHAR(50),
ContactName VARCHAR(50),
Country VARCHAR(50)
);

-- Insert some sample data into the Customers table
INSERT INTO Customers (CustomerID, CustomerName, ContactName, Country)
VALUES (1, 'Shubham', 'Thakur', 'India'),
(2, 'Aman ', 'Chopra', 'Australia'),
(3, 'Naveen', 'Tulasi', 'Sri lanka'),
(4, 'Aditya', 'Arpan', 'Austria'),
(5, 'Nishant. Salchichas S.A.', 'Jain', 'Spain');

-- Create a stored procedure named "GetCustomersByCountry"
CREATE PROCEDURE GetCustomersByCountry
@Country VARCHAR(50)
AS
BEGIN
SELECT CustomerName, ContactName
FROM Customers
WHERE Country = @Country;
END;

-- Execute the stored procedure with parameter "Sri lanka"
EXEC GetCustomersByCountry @Country = 'Sri lanka';

Note: You will need to make sure that the user account has the necessary privileges to create a database. You can try logging in as a different user with administrative privileges or contact the database administrator to grant the necessary privileges to your user account. If you are using a cloud-based database service, make sure that you have correctly configured the user account and its permissions.

Output:

CustomerName Contact Name
Naveen Tulasi

Important Points About SQL Stored Procedures

  • A stored procedure is a prepared SQL code that you can save, so the code can be reused over and over again.
  • Stored procedures allow for code that is used repeatedly to be saved on the database and run from there, rather than from the client. This provides a more modular approach to database design.
  • Since stored procedures are compiled and stored in the database, they are highly efficient. SQL Server compiles each stored procedure once and then reutilizes the execution plan. This leads to tremendous performance boosts when stored procedures are called repeatedly.
  • Stored procedures provide better security to your data. Users can execute a stored procedure without needing to execute any of the statements directly. Therefore, a user can be granted permission to execute a stored procedure without having any permissions on the underlying tables.
  • Stored procedures can reduce network traffic and latency, boosting application performance. A single call to a stored procedure can execute many statements.
  • Stored procedures have better support for error handling.
  • Stored procedures can be used to provide advanced database functionality, such as modifying data in tables, and encapsulating these changes within database transactions.

Previous Article
Next Article

Similar Reads

SQL | Difference between functions and stored procedures in PL/SQL
Prerequisite: Procedures in PL/SQLFunctions in PL/SQL.Difference between functions and stored procedures in PL/SQL Differences between Stored procedures(SP) and Functions(User-defined functions (UDF)): 1. SP may or may not return a value but UDF must return a value. The return statement of the function returns control to the calling program and ret
3 min read
Advantages and Disadvantages of Using Stored Procedures - SQL
A Stored Procedure is a type of code in SQL that can be stored for later use and can be used many times. So, whenever you need to execute the query, instead of calling it you can just call the stored procedure. You can also pass parameters to a stored procedure, so that the stored procedure can act based on the parameter values that is passed. Synt
3 min read
Some Useful System Stored Procedures in SQL
Some Useful System Stored Procedures in SQL. These procedures are built-in procedures and will help to extract the definition and dependencies of the existing user-defined stored procedures. sp_help : This will display the Stored procedure Name, Schema Name, created date, and Time or if there are any parameters, then Parameter Name, Data Type, Leng
2 min read
Stored Procedures classification based on Input and Output Parameters in SQL Server
Stored Procedure: The stored procedure has the following key points as follows. It is a collection of SQL statements such as if you want to write and read data from a database then you can use create a statement for write and select statement for reading the data from database and SQL command logic for the same, which is compiled and stored on the
2 min read
SQL VS ADO.NET With Stored Procedures
Stored Procedures have been used as a solution for so many problems, performance issues and not being able to separate the business Logic and transaction management. Stored Procedure tries to solve this major problem while developing a website. In .NET when we want to create a website or desktop application and when we have to query the database we
6 min read
How to Execute SQL Server Stored Procedure in SQL Developer?
A stored procedure is a set of (T-SQL ) statements needed in times when we are having the repetitive usage of the same query. When there is a need to use a large query multiple times we can create a stored procedure once and execute the same wherever needed instead of writing the whole query again. In this article let us see how to execute SQL Serv
2 min read
How to SQL Select from Stored Procedure using SQL Server?
There may be situations in SQL Server where you need to use a stored procedure to get data from a SQL query. For direct data selection from a stored procedure within a query, SQL Server offers options like OPENQUERY and OPENROWSET. The usual way is running the stored procedure independently and then querying the outcomes. The idea of utilizing SQL
3 min read
Procedures in PL/SQL
PL/SQL procedures are reusable code blocks that perform specific actions or logic within a database environment. They consist of two main components such as the procedure header which defines the procedure name and optional parameters and the procedure body which contains the executable statements implementing the desired business logic. In this ar
5 min read
Use of Single Quotes for Stored Procedure Parameters in SQL Server
Whenever any value is passed to the variable or column of character data type, the string value has single quotes('') around them otherwise it will through an error. Below we will discuss this feature (Use of Single Quotes for Stored Procedure Parameters in SQL Server) of SQL Server. Example 1: DECLARE @inp VARCHAR(100) SET @inp = 'GeeksforGeeks' S
2 min read
How to Create and Call a Stored Procedure in SQL?
With this article, we will learn how to Create and Call a Stored Procedure in SQL. For this article, we are going to use MSSQL as our database server. What is a Stored Procedure?A stored procedure is a pre-written SQL query that can be called multiple times and will run as the same. Like we can create a Stored procedure for Insert, select, update i
2 min read
SQL Query to Rename Stored Procedure
Stored Procedure is a saved SQL code. It is created to save time as we can use it again and again without writing the whole query. In this article, we will see how to Rename a Stored Procedure. To create a Procedure:Syntax: CREATE PROCEDURE procedure_name AS SELECT * FROM table_name;SQL query whose procedure needs to be created is always written af
2 min read
How to Export Data to the .CSV File Using SQL Server Stored Procedure?
CSV (Comma-separated values) is a file that consists of plain text data in which data is separated using comma(,). It is also known as Comma Delimited Files because comma act as a delimiter for CSV files. Here we will see, the process of exporting Data to the .CSV file using the SQL Server Stored Procedure. Step to Export Data to the .CSV File Usin
2 min read
How to Modify a Stored Procedure in SQL Server?
In this article, we will learn to modify the created stored procedure in MS SQL.You can modify the Stored Procedure in two ways. one is by using a client called SSMS and other way is by using T-SQL statements + SSMS in MS SQL Server. Method 1: Using SQL Server Management Studio (SSMS) to Modify the Stored ProcedureIn Object Explorer, connect to an
3 min read
Different types of Procedures in MySQL
A procedure is a subroutine (like a subprogram) in a regular scripting language, stored in a database. In the case of MySQL, procedures are written in MySQL and stored in the MySQL database/server. A MySQL procedure has a name, a parameter list, and SQL statement(s). There are four different types of MySQL procedures: 1. Procedure with no parameter
5 min read
What are Stand-Alone Procedures?
Stand-Alone procedures are fundamental components in modern database systems. They make­ things organized, fast, and safe. Learning about the­se procedures he­lps people managing databases to cre­ate good ones. Using simple proce­dures right means data work flows smoothly. In this article, we will see about stand-alone procedures. It will cove­r wh
5 min read
Difference between Structured Query Language (SQL) and Transact-SQL (T-SQL)
Structured Query Language (SQL): Structured Query Language (SQL) has a specific design motive for defining, accessing and changement of data. It is considered as non-procedural, In that case the important elements and its results are first specified without taking care of the how they are computed. It is implemented over the database which is drive
2 min read
Configure SQL Jobs in SQL Server using T-SQL
In this article, we will learn how to configure SQL jobs in SQL Server using T-SQL. Also, we will discuss the parameters of SQL jobs in SQL Server using T-SQL in detail. Let's discuss it one by one. Introduction :SQL Server Agent is a component used for database task automation. For Example, If we need to perform index maintenance on Production ser
7 min read
SQL vs NO SQL vs NEW SQL
SQL stands for Structured Query Language. Which is based on relational algebra and schema is fixed in this which means data is stored in the form of columns and tables. SQL follows ACID properties which means Atomicity, Consistency, Isolation, and Durability are maintained. There are three types of languages present in SQL : Data Definition Languag
2 min read
MySQL | Creating stored function
The CREATE FUNCTION statement is used for creating a stored function and user-defined functions. A stored function is a set of SQL statements that perform some operation and return a single value. Just like Mysql in-built function, it can be called from within a Mysql statement. By default, the stored function is associated with the default databas
2 min read
Stored Procedure for prime numbers in MYSQL
In this article, you will see how you can write the logic of stored procedure to generate prime numbers for any given input. Title : Given a number N print all the prime number (<=N) separated by comma (, ) using Stored Procedure in MYSQL. Example-1 : Input : N = 10 Output : 2, 3, 5, 7 Example-2 : Input : N = 20 Output : 2, 3, 5, 7, 11, 13, 17,
2 min read
How Data is Stored in Hierarchical Database?
Answer: In a hierarchical database, data is organised in a tree with a root record, parent-child relationships, and efficient access via unique keys.Root Record: A hierarchical database starts with a single root record, serving as the top-level entity in the hierarchy.Segments or Fields: Each record is divided into segments or fields, representing
1 min read
Difference Between Stored and Derived Attribute
While using databases, there is always a clear difference between stored and derived attributes, and this makes the work of managing the data easier. Stored attributes are attributes whose values are stored within the database while derived attributes use values that are stored in the database to arrive at their values. This article will, therefore
5 min read
SQL SERVER – Input and Output Parameter For Dynamic SQL
An Input Parameter can influence the subset of rows it returns from a select statement within it. A calling script can get the value of an output parameter. An aggregate function or any computational expression within the stored process can be used to determine the value of the output parameter. A parameter whose value is given into a stored proced
3 min read
Difference between T-SQL and PL-SQL
1. Transact SQL (T-SQL) : T-SQL is an abbreviation for Transact Structure Query Language. It is a product by Microsoft and is an extension of SQL Language which is used to interact with relational databases. It is considered to perform best with Microsoft SQL servers. T-SQL statements are used to perform the transactions to the databases. T-SQL has
3 min read
SQL Server | Convert tables in T-SQL into XML
In this, we will focus on how tables will be converted in T-SQL into XML in SQL server. And you will be able to understand how you can convert it with the help of command. Let's discuss it one by one. Overview :XML (Extensible Markup Language) is a markup language similar to HTML which was designed to share information between different platforms.
2 min read
SQL - SELECT from Multiple Tables with MS SQL Server
In SQL we can retrieve data from multiple tables also by using SELECT with multiple tables which actually results in CROSS JOIN of all the tables. The resulting table occurring from CROSS JOIN of two contains all the row combinations of the 2nd table which is a Cartesian product of tables. If we consider table1 contains m rows and table2 contains n
3 min read
SQL Query to Check if Date is Greater Than Today in SQL
In this article, we will see the SQL query to check if DATE is greater than today's date by comparing date with today's date using the GETDATE() function. This function in SQL Server is used to return the present date and time of the database system in a ‘YYYY-MM-DD hh:mm: ss. mmm’ pattern. Features: This function is used to find the present date a
2 min read
SQL Query to Add a New Column After an Existing Column in SQL
Structured Query Language or SQL is a standard Database language that is used to create, maintain and retrieve data from relational databases like MySQL, Oracle, SQL Server, Postgres, etc. In Microsoft SQL Server, we can change the order of the columns and can add a new column by using ALTER command. ALTER TABLE is used to add, delete/drop or modif
3 min read
SQL Query to Convert Rows to Columns in SQL Server
In this article we will see, how to convert Rows to Column in SQL Server. In a table where many columns have the have same data for many entries in the table, it is advisable to convert the rows to column. This will help to reduce the table and make the table more readable. For example, Suppose we have a table given below: NAMECOLLEGEROLL NUMBERSUB
2 min read
SQL Quiz : Practice SQL Questions Online
This SQL quiz covers various topics like SQL basics, CRUD operations, operators, aggregation functions, constraints, joins, indexes, transactions, and query-based scenarios. We've included multiple-choice questions, fill-in-the-blank questions, and interactive coding challenges to keep things interesting and challenging. Whether you're a beginner l
3 min read
Article Tags :