tags:

views:

29

answers:

2

Hello Experts i have A Sp , which Contains lot of if/else Condition Please help me how to use Switch Case in T-SQL In where Clause. here is my Query

if (@Form ='page.aspx')
begin
select 
    DT.Column,DST.Column1,
    DST.Code  from Table DT
join Table2 DST 
    on DT.ID= DST.ID
where 
    DT.code = 'XX1'
    and DT.CDID = @cdid
end

 if (@Form ='Page2.aspx')
begin
select 
    DT.Column,DST.Column1,
    DST.Code  from Table DT
join Table2 DST 
    on DT.ID= DST.ID
where 
    DT.code = 'XX2'
    and DT.CDID = @cdid
end

Please Help me, Any pointer or suggestion would be really helpful thanks

A: 
declare @dtCode varchar(255)
select @dtCode = 
   CASE @Form 
      WHEN 'page.aspx' then 'XX1' 
      WHEN 'page2.aspx' then 'XX2' 
      ELSE 'NoIdea'
   END

select
    DT.Column,DST.Column1,
    DST.Code  from Table DT
join Table2 DST 
    on DT.ID= DST.ID
where 
    DT.code = @dtCode
    and DT.CDID = @cdid

Note: I have written this with help of notepad & not used Query Analyzer to check for any syntax errror. But, I hope you get the idea (to not repeat the SQL statements when the only thing that changes is the value of dtCode).

shahkalpesh
Thanks it helped, If i need to Add other operator other than = like DT.code <> 'zz' AND DT.code <> 'zz2' in then condition ??
Monu
+1  A: 

For this particular query you could write

select

        DT.Column,DST.Column1,
        DST.Code  from Table DT

  join Table2 DST 

        on DT.ID= DST.ID
  where 

              DT.code = case @Form when 'page.aspx' then 'XX1' else 'XX2' end
 and DT.CDID = @cdid
Phil Bennett
Can we add mutiple condtion in then where (DST.Code = 'LICVA' OR DST.Code = 'CLI'
Monu
you can substitute a valid boolean expression after the case keyword. case (@Form = 'page.aspx' or @Form = 'page2.aspx') when 0 then ... else ... end
Phil Bennett
See http://msdn.microsoft.com/en-us/library/ms181765.aspx for the documentation.
Phil Bennett