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
 Case in where help

Author  Topic 

Hommer
Aged Yak Warrior

808 Posts

Posted - 2013-03-01 : 11:11:22
Hi, my dear teammates,

I can use a big help here.

declare @str_sem as nvarchar(10) ='full'
--other values are 'first', 'second'

Here are they should be:
Select col1 from mytable
where TERM_CODE not in ('') --when @str_sem = 'full', i.e. return everything

where TERM_CODE not in ('Q3', 'S2', 'Q4') --when @str_sem = 'first'

where TERM_CODE not in ('S1','Q1','Q2') --when @str_sem = 'second'

All I have come up with is this:

where TERM_CODE not in (case @str_sem when 'full' then ''
when 'first' then 'S2','Q3','Q4'
when 'second' then 'S1','Q1','Q2' )

but getting incorrect syntax. One of them said: an expression of non-boolean type specified in a context where a condition is expected.

Thanks!

webfred
Master Smack Fu Yak Hacker

8781 Posts

Posted - 2013-03-01 : 11:23:02
select col1 from mytable
where
(@str_sem = 'full')
or
(@str_sem = 'first' and Term_Code not in ('Q3', 'S2', 'Q4'))
or
(@str_sem = 'second' and Term_code not in ('S1','Q1','Q2'))


Too old to Rock'n'Roll too young to die.
Go to Top of Page

Hommer
Aged Yak Warrior

808 Posts

Posted - 2013-03-01 : 11:29:35
Thank you for the reply, but that is not the answer.

@str_sem is not a direct condition in the where clause. It is only used to derive the term code list.

My revised version looks like this, but the second and third case here only can take single value, i.e. 'S2' or 'S2,S3', but not 'S2','S3' which is what I need.

select clo1 from mytable
where (TERM_CODE not in (case @str_sem when 'full' then '' end)
or
TERM_CODE not in (case @str_sem when 'first' then 'S2' end)
or
TERM_CODE not in (case @str_sem when 'second' then 'S1' end)
)
Go to Top of Page

webfred
Master Smack Fu Yak Hacker

8781 Posts

Posted - 2013-03-01 : 11:40:46
So did you try my given solution and it didn't work or did you see it and you did know it won't work?

My bet: it works but you are not able to think out of the box...


Too old to Rock'n'Roll too young to die.
Go to Top of Page

Hommer
Aged Yak Warrior

808 Posts

Posted - 2013-03-01 : 11:47:02
Webfred,

Thanks! Your solution worked!

I saw it but did not realized your AND between $Str_sem and term_code is conditional checking the input. My bad:).
Go to Top of Page

webfred
Master Smack Fu Yak Hacker

8781 Posts

Posted - 2013-03-01 : 11:50:24
welcome


Too old to Rock'n'Roll too young to die.
Go to Top of Page
   

- Advertisement -