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
 SQL with Search Parameter

Author  Topic 

t0ze
Starting Member

10 Posts

Posted - 2010-11-18 : 09:58:03
Hi all,

I was wondering if it is possible to make one simple query using a parameter wich will be used on "where" statment. That will have two different behaviors.

Imagine something like this

**** TABLE1****
ProductId | Price|
1|12|
2|32|
3|23|
4|23|

1) scenario; getting the all list
SELECT * FROM TABLE1
WHERE PorductId = (no product specified)

RESULT: This will return all products

2) scenario; getting one product
SELECT * FROM TABLE1
WHERE PorductId = 4(4 is parameter, sent to the query)

RESULT: Product 4 | Price 23

Conclusion; How do i build one query that allows this two diffrents results ?

Best regards

jimf
Master Smack Fu Yak Hacker

2875 Posts

Posted - 2010-11-18 : 10:08:46
Don't know how smart this is, but it'll work

Where ProductID = @parameter or(@parameter is null and 1=1)

Jim

Everyday I learn something that somebody else already knew
Go to Top of Page

t0ze
Starting Member

10 Posts

Posted - 2010-11-18 : 10:18:03
Hi Jim, tks for the reply

It should be something like this ?

SELECT * FROM TABLE1
WHERE PorductId = @Parameter

(it doesn't returns anything, because the Parameter is Null)

I tried

SELECT * FROM TABLE1
WHERE ProductId = @parameter is null and 1=1

(error)

Can you give me an example using TABLE1 ?
Go to Top of Page

ahmeds08
Aged Yak Warrior

737 Posts

Posted - 2010-11-18 : 10:41:20
in the where condition mention both the parameters by using OR operator.
example:where parameter=@parameter OR parameter=''
Go to Top of Page

jimf
Master Smack Fu Yak Hacker

2875 Posts

Posted - 2010-11-18 : 11:01:52
use the code I wrote, not just a piece of it

Where ProductID = @parameter or(@parameter is null and 1=1)

Jim

Everyday I learn something that somebody else already knew
Go to Top of Page

t0ze
Starting Member

10 Posts

Posted - 2010-11-18 : 12:38:12
@ahmeds08 and @Jim

Tks for the help, problem solved, with;

where parameter=@parameter OR parameter=''

Tks to both of u!
Go to Top of Page

X002548
Not Just a Number

15586 Posts

Posted - 2010-11-18 : 12:40:05
Parameter = COALESCE(@Paramter,Parameter)

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


Want to help yourself?

http://msdn.microsoft.com/en-us/library/ms130214.aspx

http://weblogs.sqlteam.com/brettk/

http://brettkaiser.blogspot.com/


Go to Top of Page
   

- Advertisement -