Switch Case in T-SQL In where Clause
Hello Ex开发者_如何学Pythonperts 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
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
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).
精彩评论