x
login about faq Site discussion (meta-askssc)

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
314 17 30 42

(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
14.3k 16 20 29

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.

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



Facebook logo Follow Ask SSC on Facebook
Find Ask SSC on Google+
linkedin logo Find us on LinkedIn

Topics:

x912

asked: Aug 10 '12 at 02:26 PM

Seen: 341 times

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

Copyright © 2002-2012 Simple Talk Publishing. All Rights Reserved. If you have any queries, please contact the site administrators.
Ask SQL Server Central is a community service provided by Red Gate.