Monday, April 4, 2011

Optional Paramertes Queries in SQL

We often require to implemnet some search mechanism , in which we provide some input parameters and result set includes result based on those parameters
if we provide all parameters and use all of them in our select query then everything is good, but when we say use can provide some of them and others will not be a part of select statement , here we have some confusion
there are two approaches for this scenerio
No 1 is use IsNull Check
Say we have a parameter @Id and a column Id in table we can write query like
Select * from Employee
Where Id=IsNLL(@Id,Id)
So here if @id parameter is not provided and will contain null , no search criteria will be applied and all employees will be returned
this thing can be exteneded to multiple parameters as well like
Select * from Employee
Where Id=IsNLL(@Id,Id)
AND Name = ISNULL(@Name,Name)
Problem
this is good for all those table columns which does not contain NULl ,
but will fail on those column fields which can contain null values
so in order to avoid such mistakes we can use above queries by modifying a bit
No 2

Select * from Employee
Where ( @Id is null or Id=@Id) AND
(@Name is null or Name=@Name)

No comments:

Post a Comment