I need to write a stored procedure that will search a table based on optional parameters Using sql server 2008.
There will be two modes
- basic search mode (we just pass some text)
-
advanced search mode (Optional parameters are used NOT SearchText is used.)
For testing I am using the AdventureWorks.Person.Contact table
Would you write something like below if not can you make suggestions how to improve it?
Thanks a lotALTER PROCEDURE SearchPeople @SearchText nvarchar(200)=NULL, --- only used in basic search mode @SearchMode bit, @FirstName varchar(50)=NULL, @LastName varchar(50)=NULL, @EmailAddress varchar(50)=NULL, @Phone nvarchar(25)=NULL
AS
IF @SearchMode=0
BEGIN
print 'BASIC SEARCH'
SELECT *
FROM [Person].[Contact]
WHERE (FirstName LIKE '%' + @SearchText + '%'
OR LastName LIKE '%' + @SearchText + '%'
OR EmailAddress LIKE '%' + @SearchText + '%'
OR Phone LIKE '%' + @SearchText + '%')
END
ELSE
BEGIN
print 'ADVANCED SEARCH'
SELECT *
FROM [Person].[Contact]
WHERE (FirstName =@FirstName OR @FirstName IS NULL)
AND (LastName =@LastName OR @FirstName IS NULL)
AND (EmailAddress =@EmailAddress OR @EmailAddress IS NULL)
AND (Phone =@Phone OR @Phone IS NULL)
END
I agree with Joe. Your solution would lead to parameter sniffing. one way to solve param sniffing is to split into basic and advance search stored procedure. But even then you would need to use Dynamic SQL in the advanced search stored procedure to avoid parameter sniffing. I dont know about your specific situation, but if you have just one or two fields to search by, then maybe you dont need to worry about param sniffing, but if you have , lets say, more than 5 or 6 parameters you should definitely go with dynamic SQL.
so the advanced search should look something like this.
Here is a usefull article on parameter sniffing Link