Parameters can be passed to the stored procedures. This makes the procedure dynamic.
The following points are to be noted:
CREATE PROCEDURE spSelectStudent (@Course INTEGER, @Grade INTEGER)
AS
SELECT * FROM Students
WHERE Std_Course=@Course AND Std_Grade <= @Grade
GO
EXEC spSelectStudent 3, 2;
Id Name Std_Course Phone Std_Grade
3 Harri Robins 3 78788 1
4 Joe Philip 3 46456 2
(2 row(s) affected)
In the above example, the procedure is defined with two parameters. It should be noted that while executing the procedure the parameters should be passed in the same order of that in the CREATE statement. In this case, the first argument corresponds to Std_Course and second argument to Std_Grade.
EXEC spSelectStudent @Course=3, @Grade=2;
EXEC spSelectStudent @Grade=2, @Course=3;
Id Name Std_Course Phone Std_Grade
3 Harri Robins 3 78788 1
4 Joe Philip 3 46456 2
(2 row(s) affected)
Id Name Std_Course Phone Std_Grade
3 Harri Robins 3 78788 1
4 Joe Philip 3 46456 2
(2 row(s) affected)
Here since we are explicitly naming the parameters and assigning the appropriate value, the stored procedure allows the parameters to be supplied in any order.
CREATE PROCEDURE spSelectStudent1 (@Course INTEGER=2, @Grade INTEGER=3)
AS
SELECT * FROM Students
WHERE Std_Course=@Course AND Std_Grade <= @Grade
GO
EXEC spSelectStudent1;
Id Name Std_Course Phone Std_Grade
1 Joe Mathew 2 12345 2
(1 row(s) affected)
The stored procedures can be created with optional parameters with default values, so that if no values are assigned to the parameters then the default value will be taken as the value of the parameter.
In the above example, the procedure is executed without any parameter. So it takes the default parameters, which are @Course as 2, @Grade as 3.
EXEC spSelectStudent1 @Course=4, @Grade=4;
Id Name Std_Course Phone Std_Grade
2 Rock Feller 4 46565 3
(1 row(s) affected)
In the above example, the procedure takes the specified parameters of @Course as 4, @Grade as 4.