Selected topic
Stored Procedures
Prefer practical output? Use related tools below while reading.
====================================================
Stored procedures are precompiled SQL statements that can be executed multiple times with different parameters. Here's a summary of executing stored procedures and an example:
To execute a stored procedure, use the following syntax:
sql
EXEC procedure_name [(@parameter1, @parameter2, ...)];procedure_name is the name of the stored procedure to be executed.@parameter1, @parameter2, etc. are input parameters passed to the procedure.Let's create a simple stored procedure called GetEmployeeDetails that retrieves employee information based on an employee ID:
sql
CREATE PROCEDURE GetEmployeeDetails
@EmpID INT
AS
BEGIN
SELECT * FROM Employees WHERE EmpID = @EmpID;
END;
GOsql
EXEC GetEmployeeDetails @EmpID = 123;123.Stored procedures can take input parameters that are passed to them using the @ symbol. The data type of each parameter must match the data type of the corresponding variable in the procedure.
Some stored procedures may also return output parameters, which can be used to store values returned by the procedure. To declare an out parameter, use the OUTPUT keyword:
sql
CREATE PROCEDURE GetEmployeeDetails
@EmpID INT,
@Name VARCHAR(50) OUTPUT
AS
BEGIN
SELECT * FROM Employees WHERE EmpID = @EmpID;
SET @Name = (SELECT Name FROM Employees WHERE EmpID = @EmpID);
END;
GOsql
DECLARE @Name VARCHAR(50);
EXEC GetEmployeeDetails @EmpID = 123, @Name OUTPUT;
PRINT @Name; -- prints the employee namesp_executesql instead of EXEC when executing a stored procedure that takes input parameters.