âī¸ A Stored Procedure is a precompiled collection of one or more SQL statements stored in the database and executed as a single unit. Stored procedures help automate repetitive tasks, improve code reusability, enhance security, and simplify database application development.
đ What is a Stored Procedure?
A stored procedure is a named database object that contains SQL statements and optional programming logic such as variables, conditions, loops, and error handling (depending on the database system). Once created, it can be executed whenever needed without rewriting the SQL code.
Information
đ¯ Why Use Stored Procedures?
Stored procedures provide a structured and efficient way to manage database operations.
- đ Reuse SQL logic across multiple applications.
- đ Reduce duplicate SQL code.
- đ Improve performance by reusing execution plans where supported.
- đ Increase security by granting access to procedures instead of tables.
- đ Encapsulate complex business logic.
- đ Simplify database maintenance.
đ Sample Table
| StudentID | Name | Department | Age |
|---|---|---|---|
| 101 | Alice | Computer Science | 20 |
| 102 | Bob | Mathematics | 21 |
| 103 | Charlie | Physics | 19 |
đ Basic Syntax
The exact syntax depends on the database system. The following example uses SQL Server syntax.
CREATE PROCEDURE Syntax (SQL Server)
CREATE PROCEDURE procedure_name
AS
BEGIN
-- SQL statements
END;đĄ Create a Simple Stored Procedure
Create a procedure that returns all student records.
Get All Students
CREATE PROCEDURE GetStudents
AS
BEGIN
SELECT *
FROM Students;
END;âļī¸ Execute a Stored Procedure
After creating the procedure, execute it whenever the data is needed.
Execute Procedure
EXEC GetStudents;đ¯ Stored Procedure with Parameters
Parameters allow a procedure to accept input values, making it more flexible.
Procedure with Input Parameter
CREATE PROCEDURE GetStudentByDepartment
@Department VARCHAR(100)
AS
BEGIN
SELECT *
FROM Students
WHERE Department = @Department;
END;âļī¸ Execute with a Parameter
Execute Parameterized Procedure
EXEC GetStudentByDepartment
@Department = 'Computer Science';â Stored Procedure for INSERT
Stored procedures are commonly used to insert data while centralizing business rules.
Insert Student
CREATE PROCEDURE AddStudent
@Name VARCHAR(100),
@Department VARCHAR(100),
@Age INT
AS
BEGIN
INSERT INTO Students
(Name, Department, Age)
VALUES
(@Name, @Department, @Age);
END;âļī¸ Execute the INSERT Procedure
Add a Student
EXEC AddStudent
@Name = 'David',
@Department = 'Physics',
@Age = 22;đ Stored Procedure for UPDATE
Update Student Department
CREATE PROCEDURE UpdateDepartment
@StudentID INT,
@Department VARCHAR(100)
AS
BEGIN
UPDATE Students
SET Department = @Department
WHERE StudentID = @StudentID;
END;đ Procedure Workflow
| Step | Description |
|---|---|
| Create | Define and store the procedure in the database. |
| Execute | Call the procedure when needed. |
| Run SQL | The database executes the stored SQL statements. |
| Return Result | Results or status information are returned to the caller. |
âī¸ Stored Procedure vs SQL Query
| Feature | Stored Procedure | Regular SQL Query |
|---|---|---|
| Stored in Database | â Yes | â No |
| Reusable | â Yes | Limited |
| Accept Parameters | â Yes | Typically No |
| Contains Business Logic | â Yes | Usually Limited |
| Executed on Demand | â Yes | â Yes |
đŧ Real-World Example
A banking application uses a stored procedure to transfer money between two accounts. The procedure validates account balances, updates both accounts, and records the transaction, ensuring the entire operation follows the required business rules.
Conceptual Transfer Procedure
CREATE PROCEDURE TransferFunds
@FromAccount INT,
@ToAccount INT,
@Amount DECIMAL(10,2)
AS
BEGIN
-- Validate balance
-- Debit source account
-- Credit destination account
-- Record transaction
END;đī¸ Database Compatibility
| Database System | Stored Procedure Support |
|---|---|
| SQL Server | â Full support using T-SQL. |
| MySQL | â Supports stored procedures. |
| PostgreSQL | â Supports procedures (introduced in PostgreSQL 11) in addition to functions. |
| Oracle | â Full support using PL/SQL. |
| SQLite | â Does not support stored procedures. |
â ī¸ Advantages
- â Centralizes business logic.
- â Improves code reuse.
- â Reduces network traffic by executing multiple statements together.
- â Simplifies application development.
- â Can improve security through controlled access.
â ī¸ Limitations
- â Syntax differs across database systems.
- â Large procedures can become difficult to maintain.
- â Business logic tied closely to the database can reduce portability.
- â Debugging may be more challenging than application code.
Warning
â ī¸ Best Practices
Best Practice
đ Key Points to Remember
- đ Stored procedures are reusable collections of SQL statements.
- đ They can accept input parameters.
- đ They simplify complex database operations.
- đ They can improve security and code organization.
- đ Syntax and capabilities vary between database systems.
- đ They are widely used for business logic, reporting, and data manipulation.