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
 SELECT Question?

Author  Topic 

raysefo
Constraint Violating Yak Guru

260 Posts

Posted - 2010-06-30 : 08:32:40
Hi,

I want to retrieve data under some conditions like below;

SELECT T.A,T.B
FROM TABLE1 T
WHERE T.X = PARAM1 AND T.Y = PARAM2

what i need to do is, to retrieve data ;
1) if no params (PARAM1 and PARAM2) entered
2) if one of the params (PARAM1 or PARAM2) entered
3) both of the params (PARAM1 and PARAM2) entered

Is there a way to constructa single SELECT statement?

madhivanan
Premature Yak Congratulator

22864 Posts

Posted - 2010-06-30 : 08:35:03
SELECT T.A,T.B
FROM TABLE1 T
WHERE (@param1 is null or T.X = @PARAM1) AND (@param2 is null or T.Y = PARAM2)


Madhivanan

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

webfred
Master Smack Fu Yak Hacker

8781 Posts

Posted - 2010-06-30 : 08:44:14
Also consider this:
http://sqlinthewild.co.za/index.php/2009/03/19/catch-all-queries/


No, you're never too old to Yak'n'Roll if you're too young to die.
Go to Top of Page

raysefo
Constraint Violating Yak Guru

260 Posts

Posted - 2010-06-30 : 09:25:35
thanks so much both of u.
Go to Top of Page

X002548
Not Just a Number

15586 Posts

Posted - 2010-06-30 : 09:39:21
So Gila's answer is Dynamic SQL????

Couldn't M$ haven't written a hack on the optimizer like so many other things that they have done to date?

And no mention of

t.x = COALESCE(@Param1,t.x)

???

Gotta test this one

Brett

8-)

Hint: Want your questions answered fast? Follow the direction in this link
http://weblogs.sqlteam.com/brettk/archive/2005/05/25/5276.aspx

Add yourself!
http://www.frappr.com/sqlteam



Go to Top of Page

Lamprey
Master Smack Fu Yak Hacker

4614 Posts

Posted - 2010-06-30 : 11:21:02
quote:
Originally posted by X002548

And no mention of

t.x = COALESCE(@Param1,t.x)
That's the same as
t.x = CASE WHEN @Param1 IS NULL THEN t.x ELSE @Param1 END
So, CAOLESCE is not any better, unfortunatly.
Go to Top of Page
   

- Advertisement -