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, 2012 at 02:26 PM in Default

avatar image

Mohan
324 49 59 63

(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, 2012 at 03:51 PM

avatar image

TimothyAWiseman
15.6k 22 51 38

Thank you very much

Aug 10, 2012 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, 2012 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, 2012 at 04:19 PM TimothyAWiseman

@eghetto I updated it, thank you for helping me clarify.

Aug 15, 2012 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

SQL Server Central

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

Topics:

x1067

asked: Aug 10, 2012 at 02:26 PM

Seen: 829 times

Last Updated: Aug 15, 2012 at 04:20 PM

Copyright 2016 Redgate Software. Privacy Policy