Here is a snippet of what I have:
select something from myTable
where curentFlag = 'Y'
and
case when @Year2 is not NULL then
AYEAR >= @Year AND AYEAR <= @Year2
else
AYEAR= isnull(@Year ,AYEAR)
end
ADATE = ISNULL(@Date, ADATE)
But this yields:
Incorrect syntax near ‘>’.
Incorrect syntax near ‘ADATE’.
The user should be able to search by a year (equals to) or a year range. So I’m either passing in just @YEAR or both @YEAR and @YEAR2. So let’s say my data set:
DECLARE @y TABLE(AYEAR INT);
INSERT @y VALUES(2008),(2010),(2010);
Now I have these variables:
DECLARE @YEAR INT, @YEAR2 INT;
- If I pass in
@YEAR = 2008I should get 1 result. - If I pass in
@YEAR = 2010I should get 2 results. - If I pass in
@YEAR = 2008and@YEAR2 = 2010I should get all 3 results.
CASEis an expression that returns a single value. It cannot be used for control of flow logic.If you are sure that
@Yearwill always be populated and@Year2will only sometimes be populated, than this much simpler logic should work:You can try it with a very simple example: