Reputation: 2207
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
Upvotes: 1
Views: 833
Reputation: 4839
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
Upvotes: 1
Reputation: 33474
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).
Upvotes: 1