?
Solved

SQL query which will ignore null parameters

Posted on 2003-03-04
3
Medium Priority
?
2,497 Views
Last Modified: 2011-09-20
I need to write a query which will run a check on a number of fields based on parameters passed in at run time.
if a parameter to check against a field is left null, I want the query to skip the check against that particular field, hence only querying on the fields for which parameters have been entered.

e.g.

if I had:

select * from customers
where name = :param1
age = :param2
surname = :param3

and I gave it the parameters:
name= "John"
age= null
surname= "Smith"

it would only search on the name and surname fields in the customers table.

Any ideas?

Thanks.
0
Comment
Question by:the_enigma7
  • 2
3 Comments
 
LVL 2

Accepted Solution

by:
hellokns earned 400 total points
ID: 8063722
You have 2 options.

First option is using dynamic sql.

The second option is,

Have the query like this,

select * from customers
where name = ISNULL(:param1,name)
age = ISNULL(:param2,age)
surname = ISNULL(:param3,surname)

This will ignore the null of any parameter.
0
 

Author Comment

by:the_enigma7
ID: 8064908
What if the parameters are not null, but are set to be a certain value, is there any way of ignoring parameters which are set to a certain value?
0
 
LVL 2

Expert Comment

by:hellokns
ID: 8069510
You can try 'CASE' statement for that.

SELECT * FROM CUSTOMERS
WHERE name = CASE WHEN @a IS NULL THEN name
                  WHEN @a = 'ignore' THEN name
                  ELSE @a
             END

0

Featured Post

Hire Technology Freelancers with Gigs

Work with freelancers specializing in everything from database administration to programming, who have proven themselves as experts in their field. Hire the best, collaborate easily, pay securely, and get projects done right.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

What if you have to shut down the entire Citrix infrastructure for hardware maintenance, software upgrades or "the unknown"? I developed this plan for "the unknown" and hope that it helps you as well. This article explains how to properly shut down …
Ready to get certified? Check out some courses that help you prepare for third-party exams.
Using examples as well as descriptions, and references to Books Online, show the documentation available for date manipulation functions and by using a select few of these functions, show how date based data can be manipulated with these functions.
SQL Database Recovery Software repairs the MDF & NDF Files, corrupted due to hardware related issues or software related errors. Provides preview of recovered database objects and allows saving in either MSSQL, CSV, HTML or XLS format. Ensures recov…
Suggested Courses

621 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question