x

Case in where clause

SELECT * FROM CTE WHERE CREATION_DATE BETWEEN @StartDate AND @EndDate 

in the above query i need to write a case statement in where clause for the below conditions

if @show =0 then ISNULL(COST_TOTAL,0) + ISNULL(REV_TOTAL,0) = 0 
else @show =1 then R_TOTAL <= 5000 AND  ISNULL(C_TOTAL,0) + ISNULL(R_TOTAL,0) > 0
pleas do the needful
more ▼

asked Aug 10 '12 at 02:26 PM in Default

Mohan gravatar image

Mohan
324 31 48 59

(comments are locked)
10|1200 characters needed characters left

1 answer: sort voted first

You cannot use a case statement in the where clause to select which conditional is evaluated. You can however achieve something similar with OR. For instance:

(@show =0 AND ISNULL(COST_TOTAL,0) + ISNULL(REV_TOTAL,0) = 0) OR 
(@show =1 AND R_TOTAL <= 5000 AND  ISNULL(C_TOTAL,0) + ISNULL(R_TOTAL,0) > 0)

Alternatively, you could use dynamic SQL to include just the appropriate condition as you build the query.

[Edited for clarity based on helpful comments.]
more ▼

answered Aug 10 '12 at 03:51 PM

TimothyAWiseman gravatar image

TimothyAWiseman
15.5k 19 22 32

Thank you very much
Aug 10 '12 at 04:12 PM Mohan

@TimothyAWiseman: "You cannot use a case statement in the where clause." Of course you can! Something like:

SELECT
 objects.name
   ,objects.object_id
   ,objects.principal_id
   ,objects.schema_id
   ,objects.parent_object_id
   ,objects.type
   ,objects.type_desc
 FROM
 SYS.objects
 WHERE
 objects.type = CASE
 WHEN objects.type_desc = N'SYSTEM_TABLE' THEN
 N'S'
 ELSE
 NULL
 END
Aug 13 '12 at 08:10 AM eghetto
@eghetto You are right of course. I was not at all clear and I meant you can't use a case statement the way Murali was trying. You can't use it to directly select which conditional statement is evaluated.
Aug 15 '12 at 04:19 PM TimothyAWiseman
@eghetto I updated it, thank you for helping me clarify.
Aug 15 '12 at 04:20 PM TimothyAWiseman
(comments are locked)
10|1200 characters needed characters left
Your answer
toggle preview:

Up to 2 attachments (including images) can be used with a maximum of 524.3 kB each and 1.0 MB total.

New code box

There's a new way to format code on the site - the red speech bubble logo will automatically format T-SQL for you. The original code box is still there for XML, etc. More details here.

Follow this question

By Email:

Once you sign in you will be able to subscribe for any updates here

By RSS:

Answers

Answers and Comments

SQL Server Central

Need long-form SQL discussion? SQLserverCentral.com is the place.

Topics:

x977

asked: Aug 10 '12 at 02:26 PM

Seen: 614 times

Last Updated: Aug 15 '12 at 04:20 PM