Declare int @NumberofPriorYears=2;
Declare int @currentYear=2014;
SELECT
*
FROM
MyTable a
WHERE
a.FiscalYear in (
When @NumberofPriorYears is 2 then i want to pass @currentYear-@NumberofPriorYears
(ie 2014,2013,2012) or when @NumberofPriorYears
is null then pass @currentYear
ie 2014.
Appreciate any help on this.
Try this
Declare int @numberofyears=2;
Declare int @currentYear=2014;
set @currentYear = datepart(year,getdate())
SELECT
*
FROM
MyTable a
WHERE
datepart(year,a.FiscalYear) between @currentYear and @currentYear+@numberofYears
SELECT *
FROM MyTable a
WHERE @currentYear - a.FiscalYear <= ISNULL(@numberOfPriorYears, 0)
If you want to be able to pass in a previous year instead of just the current year (eg see 2011-2012 instead of 2011-2014) you can use BETWEEN
WHERE a.FiscalYear BETWEEN @currentYear - ISNULL(@numberOfPriorYears, 0) AND @currentYear
Declare int @numberofyears=2;
Declare int @currentYear=2014;
SELECT *
FROM MyTable a
WHERE
( YEAR(a.FiscalYear) >= YEAR(GETDATE()) - @numberofyears
AND
@numberofyears IS NOT NULL
)
OR
( YEAR(a.FiscalYear) = YEAR(GETDATE())
AND
@numberofyears IS NULL
)
Can you use a range?
a.FiscalYear >= @currentYear-isnull(@NumberofPriorYears,0)
and a.FiscalYear < @currentYear+1
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.