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

EmployeeIDNameAgeSalaryDepartment
1Ashish2425000Electrical
2Kirshan3230000Electrical
3Anjali2025000Electronics
4Manjulika3015000Electrical
5Katrina3718000Computer
6Esha3720000Computer
7Ankita209000Electronics
8Meenakshi3015000Computer
9Alia3716000Electronics

Create a simple Stored Procedure

SQL

CREATE PROCEDURE GetAllEmployees
AS
BEGIN
    SELECT * FROM employees;
END;   

To execute the stored procedure:

SQL

EXEC GetAllEmployees;
EmployeeIDNameAgeSalaryDepartment
1Ashish2425000Electrical
2Kirshan3230000Electrical
3Anjali2025000Electronics
4Manjulika3015000Electrical
5Katrina3718000Computer
6Esha3720000Computer
7Ankita209000Electronics
8Meenakshi3015000Computer
9Alia3716000Electronics