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
 Help needed with multiple and or

Author  Topic 

mfelicien
Starting Member

1 Post

Posted - 2009-04-02 : 12:44:12
I am having some difficulty working on a query for a website that needs to pull information from several criteria. eg
by default i need it to pull all the info and evaluate other expressions only if the variable is not null.
for eg.


select * from table where (length('var1') > 0 and (id = var1)) or (length('var2') > 0 and (size = var2)) or (length('var3') > 0 and (music = var3)) and id is not null.

for some reason this just does not work.. It always returns all the records.
I should note the value of the variables are numbers and not txt. i am not sure if that has something to do with it..
Please help.

DonAtWork
Master Smack Fu Yak Hacker

2167 Posts

Posted - 2009-04-02 : 13:22:20
Follow the first link in my signature, then restate your question.

[Signature]For fast help, follow this link:
http://weblogs.sqlteam.com/brettk/archive/2005/05/25.aspx
Learn SQL or How to sell Used Cars
For ultra basic questions, follow these links.
http://www.sql-tutorial.net/
http://www.firstsql.com/tutor.htm
http://www.w3schools.com/sql/default.asp
Go to Top of Page

madhivanan
Premature Yak Congratulator

22864 Posts

Posted - 2009-04-03 : 03:16:03
Try

select * from table where ((length('var1') > 0 and (id = var1)) or (length('var2') > 0 and (size = var2)) or (length('var3') > 0 and (music = var3))) and id is not null

Madhivanan

Failing to plan is Planning to fail
Go to Top of Page

visakh16
Very Important crosS Applying yaK Herder

52326 Posts

Posted - 2009-04-03 : 13:02:08
quote:
Originally posted by mfelicien

I am having some difficulty working on a query for a website that needs to pull information from several criteria. eg
by default i need it to pull all the info and evaluate other expressions only if the variable is not null.
for eg.


select * from table where (length('var1') > 0 and (id = var1)) or (length('var2') > 0 and (size = var2)) or (length('var3') > 0 and (music = var3)) and id is not null.

for some reason this just does not work.. It always returns all the records.
I should note the value of the variables are numbers and not txt. i am not sure if that has something to do with it..
Please help.



seems like this

select * from table
where (id = @var1 or @var1 is null)
and (size = @var2 or @var2 is null)
and (music = @var3 or @var3 is null)
and id is not null
Go to Top of Page
   

- Advertisement -