Optional parameters in sql server stored procedures Part 6804:33

  • 0
Published on June 14, 2017

Link for code samples used in the demo

Link for csharp, asp.net, ado.net, dotnet basics, mvc and sql server video tutorial playlists

Parameters of a sql server stored procedure can be made optional by specifying default values.

We wil be using table tblEmployee for this Demo.
CREATE TABLE tblEmployee
(
Id int IDENTITY PRIMARY KEY,
Name nvarchar(50),
Email nvarchar(50),
Age int,
Gender nvarchar(50),
HireDate date,
)

Insert into tblEmployee values
(‘Sara Nan’,’[email protected]’,35,’Female’,’1999-04-04′)
Insert into tblEmployee values
(‘James Histo’,’[email protected]’,33,’Male’,’2008-07-13′)
Insert into tblEmployee values
(‘Mary Jane’,’[email protected]’,28,’Female’,’2005-11-11′)
Insert into tblEmployee values
(‘Paul Sensit’,’[email protected]’,29,’Male’,’2007-10-23′)

Name, Email, Age and Gender parameters of spSearchEmployees stored procedure are optional. Notice that, we have set defaults for all the parameters, and in the “WHERE” clause we are checking if the respective parameter IS NULL.
Create Proc spSearchEmployees
@Name nvarchar(50) = NULL,
@Email nvarchar(50) = NULL,
@Age int = NULL,
@Gender nvarchar(50) = NULL
as
Begin
Select * from tblEmployee where
(Name = @Name OR @Name IS NULL) AND
(Email = @Email OR @Email IS NULL) AND
(Age = @Age OR @Age IS NULL) AND
(Gender = @Gender OR @Gender IS NULL)
End

Testing the stored procedure
1. Execute spSearchEmployees – This command will return all the rows
2. Execute spSearchEmployees @Gender = ‘Male’ – Retruns only Male employees
3. Execute spSearchEmployees @Gender = ‘Male’, @Age = 29 – Retruns Male employees whose age is 29

Enjoyed this video?
"No Thanks. Please Close This Box!"