Link to home
Start Free TrialLog in
Avatar of rivkamak
rivkamakFlag for United States of America

asked on

double case statement

I have a case statement I am trying to use to prioritize the ordering.
How can I add 2 clauses to the case?

When I do this is works:
CASE WHEN state = @stateAb THEN 0 ELSE 1 END

when I try to do this, I don't get it returned state = only
CASE WHEN state = @stateAb and usedForCity = 0 THEN 0 ELSE 1 END
Avatar of Dulton
Dulton

Try nesting the case statements.... what you're trying works in later versions of SQL, not familiar with 2005 enough to say if this was added later. the below should work though.
case when state=@stateAb THEN CASE WHEN usedForCity=0 THEN 0 ELSE 1 END ELSE 1 END

Open in new window

Avatar of Jim Horn
>when I try to do this, I don't get it returned state = only
Offhand the syntax appears correct, assuming state and @stateAb does not contain a NULL value.  If there are NULLs, then you'll have to use the ISNULL function to handle them.   Can you post your full T-SQL?

In case it helps, an example of nesting CASE statements is in SQL Server CASE Solutions, do a find on 'CASE blocks can also be nested within themselves'.

>use to prioritize the ordering.
Also, the section below that deals with CASE in an ORDER BY clause.
Avatar of rivkamak

ASKER

select  top 100 percent * into #t1 from k4kReviewsForSite2013 ORDER BY
   -- First sort position
 CASE WHEN state = @stateAb THEN 0 ELSE 1 END
 
 select row_number() over( order by (select 1)) rn, *  into #t2
from #T1 

--select * from #t1
--select * from #t2

select * from #T2 where rn between @startNum and @endNum --order by idforstate

Open in new window


when I write to the temporary table  it works the first way.
when when I add the second clause, i lose the correct ordering.
Define 'the correct ordering'.
right ordering is only if state still shows up first.
Perhaps you could post some sample data and your expected results to help clarify your intent for us?
ASKER CERTIFIED SOLUTION
Avatar of PortletPaul
PortletPaul
Flag of Australia image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial