What is a stored procedure in SQL Server and how to create one?
What is a stored procedure in SQL Server and how to create one?
736
16-May-2023
Updated on 21-Nov-2023
Aryan Kumar
21-Nov-2023In SQL Server, a stored procedure is a precompiled collection of one or more SQL statements that perform a specific task. Stored procedures are used to encapsulate and organize SQL code, improve code reusability, and enhance security. They can accept input parameters, return output parameters, and execute a series of SQL statements as a single unit of work.
Here's how you can create a simple stored procedure in SQL Server:
Syntax:
Example: Let's create a stored procedure that retrieves employees from a table based on a specified department:
In this example:
CREATE PROCEDURE GetEmployeesByDepartment: This line declares the name of the stored procedure.
@deptName NVARCHAR(50): Here, @deptName is an input parameter of type NVARCHAR(50) that represents the department name.
AS: Indicates the beginning of the stored procedure's body.
SELECT EmployeeID, FirstName, LastName FROM Employees WHERE Department = @deptName;: This is the SQL statement inside the stored procedure. It retrieves employee information based on the specified department.
To execute the stored procedure, you can use the EXEC or EXECUTE statement:
This executes the GetEmployeesByDepartment stored procedure with the department name parameter set to 'HR'.
Advantages of Stored Procedures:
Code Reusability:
Improved Performance:
Security:
Modularity:
Encapsulation:
Remember to choose meaningful names for your stored procedures and follow best practices to enhance code readability and maintainability.