Important alert: (current site time 7/15/2013 7:32:20 PM EDT)
 

VB icon

A search or find using optional parameters

Email
Submitted on: 8/6/2003 9:47:25 AM
By: Andrew Corley  
Level: Intermediate
User Rating: By 1 Users
Compatibility: SQL Server 2000, SQL Server 7.0, SQL Server 6.5 and earlier
Views: 21220
 
     This stored procedure demonstrates how to create a search that accepts multiple optional parameters. Only parameters that are provided with values will be used to filter the results. This is useful for dynamic searches when the user selects or provides values for one or more fields to be searched, but not all of the fields are required.

 
code:
Can't Copy and Paste this?
Click here for a copy-and-paste friendly version of this code!
 
Terms of Agreement:   
By using this code, you agree to the following terms...   
  1. You may use this code in your own programs (and may compile it into a program and distribute it in compiled format for languages that allow it) freely and with no charge.
  2. You MAY NOT redistribute this code (for example to a web site) without written permission from the original author. Failure to do so is a violation of copyright laws.   
  3. You may link to this code from another website, but ONLY if it is not wrapped in a frame. 
  4. You will abide by any additional copyright restrictions which the author may have placed in the code or code's description.
				
--**************************************
-- Name: A search or find using optional parameters
-- Description:This stored procedure demonstrates how to create a search that accepts multiple optional parameters. Only parameters that are provided with values will be used to filter the results. This is useful for dynamic searches when the user selects or provides values for one or more fields to be searched, but not all of the fields are required.
-- By: Andrew Corley
--
-- Inputs:Using the standard pubs..authors SQL server table, accepts a last name, first name, zip code, and contract flag as varchar values.
--
-- Returns:A result set filtered only by the parameters that were given values.
--
-- Assumes:This should work in SQL 6.5, but I could only test this using SQL Server 2000 with the database set to 65 compatibility level. This code was written explicitly to avoid using the SQL EXEC string function for several reasons. 1) Do not assume that this query method hampers performance. In large tables with proper indexes, this query performs well. 2) By using a string exec, the SQL code in the exec statement is not precompiled and optimized like a stored procedure. 3) The EXEC statement leaves an application open to SQL Injection attacks, something that hackers can easily exploit. <http://www.sitepoint.com/article/794> 4) Users should not be granted direct access to tables, which is required with the EXEC string statement. 5) All access to tables should be via stored procedures, which the users execute. As you can see although the string EXEC function is very powerful, it is does not fit within enterprise and web applications due to security, reliability and performance issues.
--
-- Side Effects:Only a large table, the like clause may cause performance issues. Also, converting numeric, bit, and datetime fields to char(n) for the LIKE test in the where clause may cause performance issues. Additional indexes and/or computed fields may resolve these issues.
--
--This code is copyrighted and has-- limited warranties.Please see http://www.Planet-Source-Code.com/vb/scripts/ShowCode.asp?txtCodeId=737&lngWId=5--for details.--**************************************

CREATE PROCEDURE usp_FindAuthor
	
	/* All parameters are optional */
	@LastName varchar(200) = NULL,
	@FirstName varchar(200) = NULL,
	@ZipCode varchar(200) = NULL,
	@Contract varchar(200) = NULL
AS
IF @LastName IS NULL
BEGIN
	/* If the parameter is null, then this statement will
		cause the select to not filter by last name.	 */
	SET @LastName = '%'
END
ELSE
BEGIN
	/* Since we want to search for this last name, add the
		wildcard to require the select to return all
		last names that begin with this value.		*/
	SET @LastName = @LastName + '%'
END
IF @FirstName IS NULL
BEGIN
	/* If the parameter is null, then this statement will
		cause the select to not filter by first name.	 */
	SET @FirstName = '%'
END
ELSE
BEGIN
	/* Since we want to search for this last name, add the
		wildcard to require the select to return all
		first names that begin with this value.		*/
	SET @FirstName = @FirstName + '%'
END
IF @ZipCode IS NULL
BEGIN
	/* If the parameter is null, then this statement will
		cause the select to not filter by zip code.	 */
	SET @ZipCode = '%'
END
ELSE
BEGIN
	/* Since we want to search for this zip code, add the
		wildcard to require the select to return all
		zip codes that begin with this value.		*/
	SET @ZipCode = @ZipCode + '%'
END
IF @Contract IS NULL
BEGIN
	/* If the parameter is null, then this statement will
		cause the select to not filter by contract.	 */
	SET @Contract = '%'
END
	/* Since we want to search for contracted authors and
		this is a bit field, do not add the wildcard.
		The same is true for numeric fields and dates. 	*/
SELECT 
	au_id, 
	au_lname, 
	au_fname, 
	phone, 
	address, 
	city, 
	state, 
	zip, 
	contract 
FROM 
	pubs..authors	WITH (NOLOCK)
WHERE
	au_lname LIKE @LastName
	AND
	au_fname LIKE @FirstName
	AND
	zip LIKE @ZipCode
	AND
	contract LIKE @Contract


Report Bad Submission
Use this form to tell us if this entry should be deleted (i.e contains no code, is a virus, etc.).
This submission should be removed because:

Your Vote

What do you think of this code (in the Intermediate category)?
(The code with your highest vote will win this month's coding contest!)
Excellent  Good  Average  Below Average  Poor (See voting log ...)
 

Other User Comments

10/25/2003 1:50:41 PMBasel Nimer

an easier solution will be

CREATE PROCEDURE usp_FindAuthor

/* ALL parameters are optional */
@LastName varchar(200) = NULL,
@FirstName varchar(200) = NULL,
@ZipCode varchar(200) = NULL,
@Contract varchar(200) = NULL
AS
SELECT
au_id,
au_lname,
au_fname,
phone,
address,
city,
state,
zip,
contract
FROM
pubs.authors WITH (NOLOCK)
WHERE
((au_lname LIKE @LastName) OR (@LastName IS NULL))
AND
((au_fname LIKE @FirstName)OR (@FirstName IS NULL))
AND
((zip LIKE @ZipCode) OR (@ZipCode IS NULL))
AND
((contract LIKE @Contract) OR (@Contract IS NULL))


Regards.

(If this comment was disrespectful, please report it.)

 
10/25/2003 3:00:11 PMBasel Nimer

and if SQL server uses short curcit evaluation, then this should be superior.

(If this comment was disrespectful, please report it.)

 
12/3/2004 3:55:01 AM

Good article for a PL/SQL walk through
(If this comment was disrespectful, please report it.)

 
12/16/2008 11:12:20 AMKazi Khalid

Try this

SELECT
au_id,
au_lname,
au_fname,
phone,
address,
city,
state,
zip,
contract
FROM
pubs..authors WITH (NOLOCK)
WHERE
au_lname LIKE isnull(@LastName ,'%') + '%'
AND
au_fname LIKE isnull(@FirstName ,'%') + '%'
AND
zip LIKE isnull(@ZipCode ,'%') + '%'
AND
contract LIKE isnull(@Contract ,'%') + '%'

(If this comment was disrespectful, please report it.)

 

Add Your Feedback
Your feedback will be posted below and an email sent to the author. Please remember that the author was kind enough to share this with you, so any criticisms must be stated politely, or they will be deleted. (For feedback not related to this particular code, please click here instead.)
 

To post feedback, first please login.