Thursday, 28 July 2011

How to use Case statement in Where clause in SQL Server

Assume the table is like this

SNOSNAMEGRADEPASS
1Kesav11
2Kishore11
3Srinath21
4Srinu31
5Sunil10
6Swapna21
7Venuka01
8Suneetha01
9Venky01
10Kamala01


@grade input takes above_0/equallto_0/allpassed

Create proc normal_proc(@grade nvarchar(10))
as
begin
   if(@grade='above_0')
      select * from tab where grade in (1,2,3) and pass=1
   else if(@grade='equallto_0')
      select * from tab where grade in (0) and pass=1
   else
      select * from tab where pass=1
end

Now usage of case statement in where clause like follows....

create proc Case_in_Where(@grade nvarchar(10))
as
begin
   select * from tab
      where ((grade=case when @grade='above_0' then 1
         when @grade='equallto_0' then 0
         else grade end)
      or (grade=case when @grade='above_0' then 2
         when @grade='equallto_0' then 0
         else grade end)
      or (grade=case when @grade='above_0' then 3
         when @grade='equallto_0' then 0
         else grade end))
      and pass=1
end

You can follow either of the procedures above mentioned but comming to huge number of comparisions in where condition "Case_in_Where" is the best option


exec check_proc 'above_0'
SNOSNAMEGRADEPASS
1Kesav11
2Kishore11
3Srinath21
4Srinu31
6Swapna21

(5 row(s) affected)


exec check_proc 'equallto_0'
SNOSNAMEGRADEPASS
7Venuka01
8Suneetha01
9Venky01
10Kamala01

(4 row(s) affected)


exec check_proc 'allpassed'
SNOSNAMEGRADEPASS
1Kesav11
2Kishore11
3Srinath21
4Srinu31
6Swapna21
7Venuka01
8Suneetha01
9Venky01
10Kamala01

(9 row(s) affected)


Tag: case in sql server, case in sql server 2005, Case with Where clause in SQL Server, using case in sql server, using case in sql server where clause

No comments:

Post a Comment

Parsing JSON w/ @ symbol in it

To read the json response like bellow @ concatenated with attribute                             '{ "@id": 1001, "@name&q...