Stored Procedure in SQL
A stored procedure in SQL is a set of SQL statements that can be stored and reused. Stored procedures allow for more complex logic than individual SQL statements and can accept parameters, allowing them to be dynamic and reusable.
The general syntax for creating a stored procedure is as follows:
SQL Syntax
CREATE PROCEDURE procedure_name AS BEGIN -- SQL statements END;
Example: Let's create a stored procedure that retrieves all employees from the employees table.
Table: employees
EmployeeID | Name | Age | Salary | Department |
---|---|---|---|---|
1 | Ashish | 24 | 25000 | Electrical |
2 | Kirshan | 32 | 30000 | Electrical |
3 | Anjali | 20 | 25000 | Electronics |
4 | Manjulika | 30 | 15000 | Electrical |
5 | Katrina | 37 | 18000 | Computer |
6 | Esha | 37 | 20000 | Computer |
7 | Ankita | 20 | 9000 | Electronics |
8 | Meenakshi | 30 | 15000 | Computer |
9 | Alia | 37 | 16000 | Electronics |
Create a simple Stored Procedure
SQL
CREATE PROCEDURE GetAllEmployees AS BEGIN SELECT * FROM employees; END;
To execute the stored procedure:
SQL
EXEC GetAllEmployees;
EmployeeID | Name | Age | Salary | Department |
---|---|---|---|---|
1 | Ashish | 24 | 25000 | Electrical |
2 | Kirshan | 32 | 30000 | Electrical |
3 | Anjali | 20 | 25000 | Electronics |
4 | Manjulika | 30 | 15000 | Electrical |
5 | Katrina | 37 | 18000 | Computer |
6 | Esha | 37 | 20000 | Computer |
7 | Ankita | 20 | 9000 | Electronics |
8 | Meenakshi | 30 | 15000 | Computer |
9 | Alia | 37 | 16000 | Electronics |