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 2008 Forums
 Transact-SQL (2008)
 conditional where clause

Author  Topic 

bloom
Starting Member

2 Posts

Posted - 2012-01-13 : 13:05:40
hi all

i've had a look around and cant really find anything that covers my issue, I may well be being an idiot but its not something ive had to do before (or if I have then I've dynamically built the sql stmt myself and then run it), so..... what I need to do is base my select stmt around 3 checkboxes, seems simple enough but I only want to use them IF the value is true (1). The columns they refer to are true/false so if they tick 1 box I wuold want the stmt to be:

select * from foo where var1 = 1

and if 2 were checked then

select * from foo where var1 = 1 or var2 = 1

and 3

select * from foo where var1 = 1 or var2 = 1 or var3 = 1

I cant just pass the value as I dont want to ever select where a var = 0 (i'll always get all the results).

I've tried case stmts but it doesnt seem to like it, the nearest I've got is:

...
AND ( @VAR = 0 Or ( @VAR <> 0 AND t1.foo = @VAR ))
...


which works for just one, but I cant figure out how to get all three working. I know I'll kick myself when I figure it out but its been a long long week and my heads gone all floppy!

<edit>I should have said this is in a stored procedure being called from SSRS, otherwise I'd have just built the stmt myself</edit>

any thoughts anyone
thanks
bloom

sunitabeck
Master Smack Fu Yak Hacker

5155 Posts

Posted - 2012-01-13 : 13:15:43
Take a look at this thread and Transact Charlie's response in that thread. To quote him: "this is one of the few times when (In my opinion) dynamic SQL is the best way to go", and I agree with him.

http://www.sqlteam.com/forums/topic.asp?TOPIC_ID=169945
Go to Top of Page

bloom
Starting Member

2 Posts

Posted - 2012-01-13 : 13:18:44
i could kiss you, i knew it would be something like that, just couldnt get my jumbled head to think straight.

thanks again
bloom
Go to Top of Page

GilaMonster
Master Smack Fu Yak Hacker

4507 Posts

Posted - 2012-01-13 : 14:28:58
And to give a bit more detail... http://sqlinthewild.co.za/index.php/2009/03/19/catch-all-queries/

--
Gail Shaw
SQL Server MVP
Go to Top of Page
   

- Advertisement -