π Introduction
When working with database in ASP.NET or C#, we often write SQL queries like:
SELECT * FROM Students
But in real projects, developers prefer using:
π Stored Procedure
In this article, you will learn:
Everything explained in very simple words π
π§ What is a Stored Procedure?
A Stored Procedure is:
π A pre-written SQL query
π Stored inside the database
π Can be executed anytime
Simple meaning:
It is like a saved function inside SQL Server.
π― Why We Use Stored Procedure?
Instead of writing SQL query again and again in application code:
We store it once in database and reuse it.
Benefits:
β Better performance
β More security
β Reusable code
β Easy maintenance
β Cleaner application code
Real-Life Example
Think like this:
You order food from restaurant.
Instead of telling recipe every time,
Chef already saved recipe.
You just say:
βMake Paneer Butter Masalaβ
Chef knows everything.
That is Stored Procedure.
π How to Create Stored Procedure in
Microsoft SQL Server
Step 1 β Create Table
CREATE TABLE Students
(
Id INT PRIMARY KEY,
Name VARCHAR(50),
Age INT
);
Step 2 β Insert Data
INSERT INTO Students VALUES (1, 'Rahul', 22);
INSERT INTO Students VALUES (2, 'Amit', 21);
INSERT INTO Students VALUES (3, 'Neha', 23);
Step 3 β Create Stored Procedure
CREATE PROCEDURE GetAllStudents
AS
BEGIN
SELECT * FROM Students;
END
Now procedure is saved in database.
βΆ How to Execute Stored Procedure
EXEC GetAllStudents;
π₯ Output
Id Name Age
1 Rahul 22
2 Amit 21
3 Neha 23
π§ Stored Procedure with Parameter
We can also pass values.
Example:
CREATE PROCEDURE GetStudentById
@Id INT
AS
BEGIN
SELECT * FROM Students WHERE Id = @Id;
END
Execute:
EXEC GetStudentById 2;
π₯ Output
Id Name Age
2 Amit 21
π Why Stored Procedure is More Secure?
If we write query directly in C#:
string query = "SELECT * FROM Students WHERE Id=" + id;
It may cause SQL Injection.
But stored procedure:
β Protects against SQL Injection
β Safer
π Simple Difference β Query vs Stored Procedure
| Normal Query | Stored Procedure |
|---|
| Written in code | Stored in DB |
| Less secure | More secure |
| Repeated code | Reusable |
| Hard to manage | Easy to maintain |
π― When Should You Use Stored Procedure?
Use it when:
β Working with large data
β Building enterprise application
β Need security
β Need better performance
β Using ASP.NET with SQL Server
π‘ Interview Questions
Common questions:
What is Stored Procedure?
Difference between Function and Stored Procedure?
Can Stored Procedure return value?
What is parameter in Stored Procedure?
π Conclusion
Stored Procedure is a powerful feature of SQL Server.
It helps to:
β Improve performance
β Increase security
β Reuse SQL logic
β Keep application clean
If you are learning ASP.NET or C#, you must understand Stored Procedures.