Stored procedures: like functions for your SQL.
A stored procedure is a batch of SQL statements created and stored on a database. You can reuse a stored procedure over and over again.
A stored procedure can accept parameters, run a query, and return results. Many users can call a stored procedure and different applications can call it with different parameter values.
What Are the Benefits of Using Stored Procedures?
Apart from allowing multiple users and applications to reuse it, a stored procedure has other benefits.
- It is easy to modify. You can change a stored procedure when necessary and these updates will be reflected for all users. Furthermore, you don’t need to redeploy your application when you modify the stored procedure.
- It reduces network traffic because the server only passes the procedure’s name over the network and not the entire query.
- It improves database security since users don’t have direct access to tables. To make changes, they need to call the stored procedure. This prevents SQL injection attacks as users can’t directly write to the underlying tables.
A database engine like MySQL has many security features you should be aware of.
Syntax of Creating a Stored Procedure in SQL Server
The syntax of creating a stored procedure is as follows:
CREATE PROCEDURE procedure_name
Run this command to execute the stored procedure.
Example of a Simple Stored Procedure in SQL Server
Here is an example of a stored procedure that selects all articles from an article database.
CREATE PROCEDURE All_Articles
SELECT * FROM Article
This is a simple example, but you can do so much more with stored procedures like accepting parameters and updating records.
How to Create a Stored Procedure That Accepts Parameters
For example, modify the simple stored procedure to accept a number as a parameter and use it to return the posts with a view count higher than the number.
CREATE PROCEDURE Popular_Articles(@views int)
SELECT * FROM Article
WHERE views_count >= _count
Use this command to execute the stored procedure with a parameter.
EXEC Popular_Articles 300;
The procedure returns the articles whose view count is higher than 300.
Learn SQL First Before Using Stored Procedures
Stored procedures let you reuse a group of SQL statements. They also improve database security, reduce network traffic, and are easy to modify.
Learning about stored procedures is therefore important, but you must first have a solid understanding of SQL.