| Lesson 11 | Executing stored procedures |
| Objective | Execute your stored procedure. |
The legacy text explains the basics of executing a stored procedure, but it relies on outdated tooling terminology (Query
Analyzer) and contains an example that passes a literal value into an output parameter, which cannot work as written.
This rewrite modernizes the lesson for SQL Server 2022 and focuses on practical execution patterns using SSMS and
EXEC/EXECUTE, including correct handling of output parameters.
You can execute (run) stored procedures from:
In Transact-SQL, execute a stored procedure with EXEC (short form) or EXECUTE:
EXEC dbo.StoredProcedureName;
If the procedure requires parameters, you must provide them when you execute it. You can pass values in two ways:
Values are provided in the same order the parameters are defined in the procedure:
EXEC dbo.usp_GetLastName 101, @EmployeeStatus OUTPUT;
Named parameters are clearer and safer, especially when procedures have multiple parameters:
EXEC dbo.usp_GetLastName
@EmployeeID = 101,
@EmployeeStatus = @EmployeeStatus OUTPUT;
Named parameters reduce mistakes because the parameter name documents your intent and you are not dependent on the original parameter order.
OUTPUT keyword when supplying an output parameter.
Throughout this module you have created and modified usp_GetLastName. Here is a concise recap of what the
procedure is intended to do.
| Attribute | Description |
| Name | usp_GetLastName |
| Type | User-defined stored procedure |
| Purpose | Returns an employee’s last name and a status value via an output parameter |
| Parameters | @EmployeeID (input), @EmployeeStatus (output, int) |
| Example definition |
|
The following script executes the procedure for @EmployeeID = 101 and captures the returned status value into a
variable:
DECLARE @EmployeeStatus int;
EXEC dbo.usp_GetLastName
@EmployeeID = 101,
@EmployeeStatus = @EmployeeStatus OUTPUT;
SELECT @EmployeeStatus AS EmployeeStatus;
This pattern works because @EmployeeStatus is a variable that can receive a value, and the call includes the
OUTPUT keyword.