SQL stored procedures are pre-compiled sets of SQL statements that can be stored in a database and executed on demand. They can accept input parameters and return multiple result sets, making them a powerful and flexible tool for interacting with a database.
To create a stored procedure in SQL, you will need to use the CREATE PROCEDURE statement. Here is an example of how you might create a simple stored procedure that accepts an input parameter and returns a result set:
Copy code
CREATE PROCEDURE GetEmployeesByDepartment
@department_name VARCHAR(50)
AS
BEGIN
SELECT * FROM employees WHERE department = @department_name;
END
This stored procedure can then be called using the EXECUTE or EXEC statement, passing in the desired value for the @department_name parameter:
Copy code
EXECUTE GetEmployeesByDepartment 'Sales';
Stored procedures can also include more complex logic, such as loops, conditional statements, and transactions, making them a useful tool for encapsulating complex business logic within a database.