473,387 Members | 1,790 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 473,387 software developers and data experts.

Disregard some parameters

Hi,

I am building a search Query which takes 7 parameters:

Lets call them @P1 .. @P7 (all Int's)

The query is a simple select query like:

SELECT * FROM MyTable WHERE (Field1 = @P1) AND (Field2 = @P2) ....

My problem is that if some parameters are -1 they shall be disregarded.

Is there any way to set a parameter to a value meaning "Anything", or do I
have to
remove the criteria from the select clause?

(In the latter case I cannot use a stored procedure, which is what I prefer)

Cheers
Gunnar


Jul 20 '05 #1
8 1210
Gunnar,

if your columns do not contain NULLs, then you can use

WHERE Field1 BETWEEN COALESCE(NULLIF(@P1,-1),-2147483648) AND
COALESCE(NULLIF(@P1,-1),2147483647)

This WHERE clause assumes that the value "-1" is your indication of a
missing parameter. If you use NULL instead of -1, then you can replace
NULLIF(@P1,-1) with @P1. It also assumes the int datatype. If the column
is of a different integer datatype (for example bigint), then the
minimum and maximum value need to be adjusted.

If your column do contain NULLs, then you can use

WHERE CASE WHEN @P1=-1 THEN 1
CASE WHEN Field1=@P1 THEN 1
ELSE 0 END = 1

But in general, the first approach will perform better.

Hope this helps,
Gert-Jan
Gunnar Liknes wrote:

Hi,

I am building a search Query which takes 7 parameters:

Lets call them @P1 .. @P7 (all Int's)

The query is a simple select query like:

SELECT * FROM MyTable WHERE (Field1 = @P1) AND (Field2 = @P2) ....

My problem is that if some parameters are -1 they shall be disregarded.

Is there any way to set a parameter to a value meaning "Anything", or do I
have to
remove the criteria from the select clause?

(In the latter case I cannot use a stored procedure, which is what I prefer)

Cheers
Gunnar


--
(Please reply only to the newsgroup)
Jul 20 '05 #2
Hi,

One way to do the trick is to write:

SELECT * FROM MyTable WHERE ((@P1 = -1) OR (Field1 = @P1)) AND ...

If @P1 is -1, the OR-clause will simply be true for all rows, effectively
ignoring the comparison with Field1.

-Jørgen

"Gunnar Liknes" <g_liknes.Tabortunderscores@g_lobal-satcom.com> skrev i en
meddelelse news:41********@news.broadpark.no...
Hi,

I am building a search Query which takes 7 parameters:

Lets call them @P1 .. @P7 (all Int's)

The query is a simple select query like:

SELECT * FROM MyTable WHERE (Field1 = @P1) AND (Field2 = @P2) ....

My problem is that if some parameters are -1 they shall be disregarded.

Is there any way to set a parameter to a value meaning "Anything", or do I
have to
remove the criteria from the select clause?

(In the latter case I cannot use a stored procedure, which is what I prefer)
Cheers
Gunnar

Jul 20 '05 #3
"Gert-Jan Strik" wrote
if your columns do not contain NULLs, then you can use

WHERE Field1 BETWEEN COALESCE(NULLIF(@P1,-1),-2147483648) AND
COALESCE(NULLIF(@P1,-1),2147483647)

This WHERE clause assumes that the value "-1" is your indication of a
missing parameter. If you use NULL instead of -1, then you can replace
NULLIF(@P1,-1) with @P1. It also assumes the int datatype. If the column
is of a different integer datatype (for example bigint), then the
minimum and maximum value need to be adjusted.

If your column do contain NULLs, then you can use

WHERE CASE WHEN @P1=-1 THEN 1
CASE WHEN Field1=@P1 THEN 1
ELSE 0 END = 1

But in general, the first approach will perform better.


Thank you both (Gert-Jan and Jørgen) for two excellent working solutions to
my problem. The COALESCE function was interesting. Will it perform better
than the "WHERE ((@P1 = -1) OR (Field1 = @P1)) "
approach?

Thanks,
Gunnar
Jul 20 '05 #4
Gunnar Liknes wrote:
Thank you both (Gert-Jan and Jørgen) for two excellent working solutions to
my problem. The COALESCE function was interesting. Will it perform better
than the "WHERE ((@P1 = -1) OR (Field1 = @P1)) "
approach?

Thanks,
Gunnar


Yes, because if the column is indexed, index seeks can be used. The OR
solution needs an index scan.

Gert-Jan
--
(Please reply only to the newsgroup)
Jul 20 '05 #5
Gunnar Liknes (g_liknes.Tabortunderscores@g_lobal-satcom.com) writes:
Thank you both (Gert-Jan and Jørgen) for two excellent working solutions
to my problem. The COALESCE function was interesting. Will it perform
better than the "WHERE ((@P1 = -1) OR (Field1 = @P1)) " approach?


Permit me to modify Gert-Jan's enthusiasm a little. It may perform better,
but I have not always be successful with it. And if the columns is not
indexed then it not matter much anyway.

The only way to find out is to benchmark.

--
Erland Sommarskog, SQL Server MVP, es****@sommarskog.se

Books Online for SQL Server SP3 at
http://www.microsoft.com/sql/techinf...2000/books.asp
Jul 20 '05 #6
"Gert-Jan Strik" wrote
Gunnar Liknes wrote:
Thank you both (Gert-Jan and Jørgen) for two excellent working solutions to my problem. The COALESCE function was interesting. Will it perform better than the "WHERE ((@P1 = -1) OR (Field1 = @P1)) "
approach?
Yes, because if the column is indexed, index seeks can be used. The OR
solution needs an index scan.


Does MS SQL perform complete boolean evaluations? If (@P1=-1) it should
not have to check if (Field1 = @P1) because the result of the statement is
already determined.

Gunnar
Jul 20 '05 #7
Gunnar Liknes (g_liknes.Tabortunderscores@g_lobal-satcom.com) writes:
Does MS SQL perform complete boolean evaluations? If (@P1=-1) it should
not have to check if (Field1 = @P1) because the result of the statement is
already determined.


The answer is that, yes, SQL Server is able to make logical shortcuts,
but that is not applicable here.

When SQL Server builds a query plan for a stored procedure, it builds
the plan for the entire procedure at once, and is thus blind to what
the actual values of variables and parameters at the time of the statement.
It does take in regard the values of parameter to build the plan, but
since it don't know whether parameter changes value in the procedure or
not, SQL Server can choose a plan which would yield the wrong result if
the parameter is changed. Moreover, since the plan is cached, the procedure
might be called with some other values the next time.

Thus if you have:

SELECT *
FROM tbl
WHERE (field1 = @p1 OR @p1 IS NULL)
AND (field2 = @p2 OR @p2 IS NULL)

It cannot look at @p1 and say "Hey @p1 is NULL, I don't have to test
Field1". So it must pick a plan where it accesses field1. No, once it
comes to the statement it could opt to not actually check field1, but
the cost is not the check - the cost is the access. In this case,
the optimizer will most like to scan the table from left to right.

Here is another example:

SELECT *
FROM tbl
WHERE @p1 = 0 OR EXISTS (SELECT *
FROM tbl2
WHERE tbl.col = tbl2.col)

Here, if @p1 is 0 we retrieve all rows from tbl, but if @p1 is 1 only
rows which has a matching row in tbl2 are to be returned. In this example,
SQL Server is actually able to avoid accessing tbl2 if @p1 is 0, since
once @p1 is evaluated, the other branch can be pruned. Note here that
is not your C-style of shortcutting - you get the same result if you
have the condition on @p1 last.

To read more about this topic, I have an article on my web site:
http://www.sommarskog.se/dyn-search.html.

--
Erland Sommarskog, SQL Server MVP, es****@sommarskog.se

Books Online for SQL Server SP3 at
http://www.microsoft.com/sql/techinf...2000/books.asp
Jul 20 '05 #8
"Erland Sommarskog" wrote.
Gunnar Liknes writes:
Does MS SQL perform complete boolean evaluations? If (@P1=-1) it should
not have to check if (Field1 = @P1) because the result of the statement is already determined.

The answer is that, yes, SQL Server is able to make logical shortcuts,
but that is not applicable here.
<snip explanation>
To read more about this topic, I have an article on my web site:
http://www.sommarskog.se/dyn-search.html.


Thank you Erland, your article was very helpful. I also found the topics of
your
other articles very interresting. I'll read the one about Arrays & Lists
when I have
some time.

Regarding search. I'll have to wait until we get more data in our database
before
I decide which search alternative to use. For now I stick to IF / OR.

Cheers
Gunnar
Jul 20 '05 #9

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

15
by: lawrence | last post by:
I wanted to test xml_parse_into_struct() so I took the example off of www.php.net and put this code up on a site: <?php $simple = <<<END <item>
6
by: Frances Del Rio | last post by:
var myform= document.formPricing; var one = "price"; alert(one); var amount = myform.one.value; the alert prints name of element fine, however, on line var amount = myform.one.value;
0
by: Pallav | last post by:
please disregard my earlier post on sine table lookup. i've located the problem. seems to be due to errors compounding in fixed-point multiply which cause wrong table lookup. thanks pallav
5
by: Jim in Arizona | last post by:
I'm getting married in mid march so know what that means!? That means that you only have about a month to meet me somewhere and take full advantage of my non-ring wearing self! Hurry! Time is...
14
by: cody | last post by:
I got a similar idea a couple of months ago, but now this one will require no change to the clr, is relatively easy to implement and would be a great addition to C# 3.0 :) so here we go.. To...
2
by: Hexman | last post by:
Hello All, Well I'm stumped once more. Need some help. Writing a simple select and update program using VB.Net 2005 and an Access DB. I'm using parameters in my update statement and when trying...
1
by: ib | last post by:
Is there a way that I can view the items/elements of a generic list in VS2005? For example, if I use STL std::vector, I am able to use the watch window to see each element in this container. But...
3
by: ib | last post by:
ICloneable::Clone returns a new instance of the object being cloned. However, it seems possible that the garbage collector could release this memory before the calling function receives a reference...
0
by: StuckOnWords | last post by:
Please disregard. Apologies.
0
by: taylorcarr | last post by:
A Canon printer is a smart device known for being advanced, efficient, and reliable. It is designed for home, office, and hybrid workspace use and can also be used for a variety of purposes. However,...
0
by: Charles Arthur | last post by:
How do i turn on java script on a villaon, callus and itel keypad mobile phone
0
by: ryjfgjl | last post by:
In our work, we often receive Excel tables with data in the same format. If we want to analyze these data, it can be difficult to analyze them because the data is spread across multiple Excel files...
0
BarryA
by: BarryA | last post by:
What are the essential steps and strategies outlined in the Data Structures and Algorithms (DSA) roadmap for aspiring data scientists? How can individuals effectively utilize this roadmap to progress...
1
by: nemocccc | last post by:
hello, everyone, I want to develop a software for my android phone for daily needs, any suggestions?
0
by: Hystou | last post by:
There are some requirements for setting up RAID: 1. The motherboard and BIOS support RAID configuration. 2. The motherboard has 2 or more available SATA protocol SSD/HDD slots (including MSATA, M.2...
0
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can...
0
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers,...
0
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.