I had an issue in my stored procedure that needs to include rows or not depending on the value of a parameter
- if
@var_exclude = 'Y'I need to show only rows thatmytable.field1 = 'N' - if
@var_exclude = 'N'I need to show all rows
I’m using the following query but doesn’t work properly
My code is like
@var_exclude varchar(1)
select mytable.field1, mytable.field2, mytable.field3, mytable.field4,mytable.field5
from mytable
Where mytable.field6 is null
and mytable.field1 is not null
and (mytable.state = @paramstate or @paramstate = 'ALL')
and mytable.field1 = Case when @var_exclude= 'Y' Then 'N' Else @var_exclude End
End
I’m confused!
Your logic handling
@var_excludeis wrong.When you pass
@var_exclude = 'Y', then your query basically gets resolved to:since in this case, the
when @var_exclude= 'Y' Then 'N'part of your CASE clause is used.If you pass anything else in, then you take the value you’re passing in; so if you pass in
@var_exclude = 'N'then your query is resolved to:since in this case the
Else @var_excludeof your CASE clause is used – and since@var_exclude = 'N', you get the exact same query as before….I would probably write this procedure something like this: