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
 SQL Server 2005 Forums
 Transact-SQL (2005)
 If condition in where clause

Author  Topic 

MiaF
Starting Member

13 Posts

Posted - 2007-02-20 : 16:56:40
I have a page that allows users to select a field and search the database. If they don't select anything, then the page will return all the records from the database.

I put a query like this:

If(@b<>-1)
Select * from tableA where B=@b;
else
Select * from tableA where B is not null;

Is there anyway I can simply this query text? Thanks a lot.

jsmith8858
Dr. Cross Join

7423 Posts

Posted - 2007-02-20 : 17:04:58
where (@b <> -1 AND B=@b) or (B is not null)

- Jeff
http://weblogs.sqlteam.com/JeffS
Go to Top of Page

MiaF
Starting Member

13 Posts

Posted - 2007-02-21 : 10:05:33
Thanks. Just a little modification:

where (@b <> -1 AND B=@b) or (@b=-1 and B is not null)
Go to Top of Page

harsh_athalye
Master Smack Fu Yak Hacker

5581 Posts

Posted - 2007-02-21 : 10:11:59
Keep in mind even though this reduces work on your side and makes query look little compact, it can cost you performance if you run it on larger table.

Harsh Athalye
India.
"The IMPOSSIBLE is often UNTRIED"
Go to Top of Page

MiaF
Starting Member

13 Posts

Posted - 2007-02-23 : 10:13:44
Are you saying that the original if...else..statement will work better?
Go to Top of Page

harsh_athalye
Master Smack Fu Yak Hacker

5581 Posts

Posted - 2007-02-23 : 10:31:17
Check the execution plan for both solutions and check which one is better.

Harsh Athalye
India.
"The IMPOSSIBLE is often UNTRIED"
Go to Top of Page
   

- Advertisement -