364,111 Members | 2129 Browsing Online
Community for Developers & IT Professionals
Bytes IT Community

WHERE clause with IN clause with CASE WHEN...

Tapan Shroff
P: 3
I am trying to use below code and it does not work... but cant live without below conditions... is there any otherway anyone knows to do the same thing?

if i pass 0 in STRID then it should show me ALL records but if i pass 1,2,5 then it should show me only records which has 1,2,5 ID's in tble.

Thanks in Advance..

DECLARE @STRID AS VARCHAR(MAX)
--SET @STRID = '1,2,3'
SET @STRID = NULL

SELECT * FROM STORES
WHERE StrID IN ( CASE WHEN @STRID = '0' THEN @STRID WHEN @STRID <> '0' THEN (SELECT * FROM FN_SPLIT_ID_STR(@STRID,',')) END )
Feb 13 '12 #1
Share this Question
Share on Google+
4 Replies


ck9663
Expert 2.5K+
P: 2,732
First, instead of the second when, use an ELSE.
Second, this
Expand|Select|Wrap|Line Numbers
  1. CASE WHEN @STRID = '0' THEN @STRID
  2.  
should be
Expand|Select|Wrap|Line Numbers
  1. CASE WHEN @STRID = '0' THEN STRID
  2.  
I'm not digging into your function.

Happy Coding!!!


~~ CK
Feb 13 '12 #2

Tapan Shroff
P: 3
Sorry that was typo, i have added else but the code suggested also did not work for me...

may be i was not clear in description ... i have changed the query little (below)...

what i need is if parameter value is 0(ZERO) then all records should display and if the parameter value is passed as (multiple ID's) then it should display only the selected records...

Please suggest...

Expand|Select|Wrap|Line Numbers
  1. DECLARE @STRID AS VARCHAR(MAX)
  2. SET @STRID = '1,2,3'
  3. --SET @STRID = '0'
  4.  
  5. SELECT * FROM STORES 
  6. WHERE (CASE WHEN @STRID = '0' THEN @STRID ELSE Store_ID END)  
  7. IN  
  8. ( CASE WHEN @STRID = '0' THEN @STRID ELSE (SELECT *
Feb 13 '12 #3

ck9663
Expert 2.5K+
P: 2,732
Use the code tag so it's readable.

I'm sure this can be refactored, but if your table is not that big, it will not matter.

Try this:
Expand|Select|Wrap|Line Numbers
  1. SELECT * FROM STORES 
  2. WHERE 
  3.    (isnull(@STRID,'0') = '0' and store_id = stored_id) or
  4.    (isnull(@STRID,'0') <> '0' and store_id in (SELECT * FROM FN_PLGBA_SPLIT_CSV(@STRID,',')))
  5.  
Only one of those condition will be true at any given point in time. I considered NULL as '0'. Just change it if necessary.

Happy Coding!!!


~~ CK
Feb 13 '12 #4

Tapan Shroff
P: 3
It worked like a charm.... Thank You so much..
Feb 14 '12 #5

Post your reply

Help answer this question



Didn't find the answer to your Microsoft SQL Server question?

You can also browse similar questions: Microsoft SQL Server