Please start any new threads on our new site at https://forums.sqlteam.com. We've got lots of great SQL Server experts to answer whatever question you can come up with.

 All Forums
 General SQL Server Forums
 New to SQL Server Programming
 Conditions in where clause

Author  Topic 

bw_sql_greenhorn
Starting Member

3 Posts

Posted - 2010-09-01 : 09:51:25
I'm writing a query that examines a table and returns data when a field is < 100, >0 and <100, or when another field is not equal to CLOSED. The query will return the data depending on a parameter passed to the query. When the parm is 1, only return rows where field is < 100, when the parm is 2, return rows with >0 and <100, etc.

Is there an way to do this in the WHERE clause? Possibly with a CASE.

Thanks for any help

Transact Charlie
Master Smack Fu Yak Hacker

3451 Posts

Posted - 2010-09-01 : 10:05:47
you could do that certainly -- with nested ORs in the WHERE clause that turn off the clause if the paramater isn't passed.

Something like

WHERE
(
@param1 = 0
OR [field1] = 'CLOSED'
)
AND (
@param2 = 0
OR [field2] < 100
)
AND (
@param3 = 0
OR [field2] BETWEEN (1 AND 99)
)



However, you might well be better doing:

1) different queries for each option
OR 2) using dynamic sql to make the query depending on paramaters.

The reason I recommend this is that you are performing a 'catch all' type of query (very common on web forms for example).

Depending on the flags if you just have one static query then the execution plan that is cached for one type of query may not be a good plan for the other type of query. If you build up a query dynamically then you should get a separate cached plan that suits that query.

for more info try:

http://www.sommarskog.se/dynamic_sql.html


Charlie
===============================================================
Msg 3903, Level 16, State 1, Line 1736
The ROLLBACK TRANSACTION request has no corresponding BEGIN TRANSACTION
Go to Top of Page
   

- Advertisement -