How to pass parameters to Stored procedures?
To pass parameters to a stored procedure in SQL Server, you can define input parameters in the stored procedure's declaration and then provide values for those parameters when executing the stored procedure. Here's an example:
Creating a stored procedure with parameters:
CREATE PROCEDURE GetEmployeesByDepartment
@DepartmentID INT
AS
BEGIN
SELECT EmployeeID, FirstName, LastName, Salary
FROM Employees
WHERE DepartmentID = @DepartmentID
END
In this example, we're creating a stored procedure named "GetEmployeesByDepartment" that expects a single input parameter, @DepartmentID, of type INT.
Executing the stored procedure with parameter values:
To execute the stored procedure and pass the parameter values, you can use the EXEC statement.
EXEC GetEmployeesByDepartment @DepartmentID = 123
In this case, we're passing the value 123 as the @DepartmentID parameter to the stored procedure.
The stored procedure will execute the SQL statement inside it, using the provided parameter value to filter the results. It will return the details of employees who belong to the specified department.
You can also pass parameters positionally instead of using named parameters:
EXEC GetEmployeesByDepartment 123
Here, the value 123 is provided as the first parameter, which corresponds to the @DepartmentID parameter based on its position in the stored procedure declaration.
Note: In addition to input parameters, stored procedures in SQL Server can have output parameters and even return result sets. Input parameters are used to pass values into the stored procedure, output parameters are used to return values from the stored procedure, and result sets are returned by executing queries within the stored procedure.