Stored Procedure in SQL
A stored procedure in SQL is a precompiled collection of one or more SQL statements stored in the database. It is used to encapsulate logic, promote code reuse, and improve performance and security.
? Key Features of Stored Procedures
Stored and executed on the server.
Can have input, output, or input-output parameters.
Can include conditional logic, loops, and transactions.
Promotes modularity and reusability.
Helps prevent SQL injection when used properly.
? Syntax (SQL Server Style)
CREATE PROCEDURE procedure_name @param1 datatype, @param2 datatype OUTPUTASBEGIN -- SQL statements SELECT ...;END;? Simple Example: Procedure Without Parameters
CREATE PROCEDURE GetAllEmployeesASBEGIN SELECT * FROM Employees;END;To execute:
EXEC GetAllEmployees;? Example: Procedure With Parameters
CREATE PROCEDURE GetEmployeeById @EmployeeID INTASBEGIN SELECT * FROM Employees WHERE EmployeeID = @EmployeeID;END;To execute:
EXEC GetEmployeeById @EmployeeID = 102;? Example: Procedure With Output Parameter
CREATE PROCEDURE GetTotalEmployees @TotalCount INT OUTPUTASBEGIN SELECT @TotalCount = COUNT(*) FROM Employees;END;To execute and get the output:
DECLARE @Count INT;EXEC GetTotalEmployees @TotalCount = @Count OUTPUT;PRINT @Count;? Modifying and Dropping a Procedure
Modify:
ALTER PROCEDURE procedure_nameASBEGIN -- New logicEND;Drop:
DROP PROCEDURE procedure_name;
? Best Practices
Use meaningful names.
Avoid hardcoding values.
Include error handling using
TRY...CATCH.Use transactions where appropriate.
Keep them modular and focused on a single task.
Would you like a stored procedure that inserts, updates, or logs something specific? I can help you build a custom one!