Parameter values can be supplied if a stored procedure is written to accept them.
The supplied value must be a constant or a variable; you cannot specify a function name as a parameter value. Variables can be user-defined or system variables such as @@spid.
The following examples demonstrate passing parameter values to the stored procedure uspGetWhereUsedProductID. The procedure expects values for two input parameters: a product ID and a date. The examples show how to pass parameters as constants and variables and also how to use a variable to pass the value of a function.
USE AdventureWorks;
GO
-- Passing values as constants.
EXEC dbo.uspGetWhereUsedProductID 819, '20050225';
GO
-- Passing values as variables.
DECLARE @ProductID int, @CheckDate datetime;
SET @ProductID = 819;
SET @CheckDate = '20050225';
EXEC dbo.uspGetWhereUsedProductID @ProductID, @CheckDate;
GO
-- Try to use a function as a parameter value.
-- This produces an error message.
EXEC dbo.uspGetWhereUsedProductID 819, GETDATE();
GO
-- Passing the function value as a variable.
DECLARE @CheckDate datetime;
SET @CheckDate = GETDATE();
EXEC dbo.uspGetWhereUsedProductID 819, @CheckDate;
GO
If you want to specify the parameters in a different order than the order they are defined in the stored procedure, you must name them. For more information, see Specifying a Parameter Name.
To specify that a parameter should return a value to the calling program, use the OUTPUT keyword. For more information, see Specifying the Direction of a Parameter.
Specifying the Order of Parameters
If you supply parameters in the form @parameter = value, you can supply them in any order. You can also omit parameters for which defaults have been supplied. If you supply one parameter in the form @parameter = value, you must supply all subsequent parameters this way. If you do not supply parameters in the form @parameter = value, you must supply them in the order given in the CREATE PROCEDURE statement.
When executing a stored procedure, the server rejects any parameters that were not included with the parameter list during procedure creation. Any parameter passed by reference (explicitly passing the parameter name) is not accepted if the parameter name does not match.
Using Default Values in Parameters
Although you can omit parameters for which defaults have been supplied, you can only truncate the list of parameters. For example, if a stored procedure has five parameters, you can omit both the fourth and the fifth parameters, but you cannot skip the fourth and still include the fifth unless you supply parameters in the form @parameter = value.
The default value of a parameter, if defined for the parameter in the stored procedure, is used when:
-
No value for the parameter is specified when the stored procedure is executed.
-
The DEFAULT keyword is specified as the value for the parameter.