?
Solved

SQL query which will ignore null parameters

Posted on 2003-03-04
3
Medium Priority
?
2,485 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
[X]
Welcome to Experts Exchange

Add your voice to the tech community where 5M+ people just like you are talking about what matters.

  • Help others & share knowledge
  • Earn cash & points
  • Learn & ask questions
  • 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

Learn how to optimize MySQL for your business need

With the increasing importance of apps & networks in both business & personal interconnections, perfor. has become one of the key metrics of successful communication. This ebook is a hands-on business-case-driven guide to understanding MySQL query parameter tuning & database perf

Question has a verified solution.

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

In the first part of this tutorial we will cover the prerequisites for installing SQL Server vNext on Linux.
It is possible to export the data of a SQL Table in SSMS and generate INSERT statements. It's neatly tucked away in the generate scripts option of a database.
Via a live example, show how to backup a database, simulate a failure backup the tail of the database transaction log and perform the restore.
Viewers will learn how to use the SELECT statement in SQL and will be exposed to the many uses the SELECT statement has.
Suggested Courses

764 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