Please start any new threads on our new site at https://forums.sqlteam.com. We've got lots of great SQL Server experts to answer whatever question you can come up with.

 All Forums
 SQL Server 2008 Forums
 Transact-SQL (2008)
 Is there a cleaner way to do this?

Author  Topic 

LaurieCox

158 Posts

Posted - 2013-06-11 : 15:52:24
I want to select two rows (this is for a report parameter) with two columns (FiscalYear, DateRange). There needs to be one row for the current fiscal year and one row for the previous fiscal year.

Our fiscal year runs from October 1st of the previous year thru September 30th. This is what I have come up with:

select YEAR(GETDATE()) as FiscalYear
, '10/1/' + CONVERT(varchar(4),YEAR(GETDATE()) - 1) +
' thru 9/30/' + CONVERT(varchar(4),YEAR(GETDATE())) as DateRange
union
select YEAR(GETDATE()) - 1 as FiscalYear
, '10/1/' + CONVERT(varchar(4),YEAR(GETDATE()) - 2) +
' thru 9/30/' + CONVERT(varchar(4),YEAR(GETDATE()) - 1) as DateRange

Which gives this output:

FiscalYear DateRange
----------- ------------------------
2012 10/1/2011 thru 9/30/2012
2013 10/1/2012 thru 9/30/2013

… which is correct, but I wonder if there might be a better way to do it. It would be nice to be able to have something that would be easier to change if I decided that I wanted X rows.

I know one option is to create a table with the data I want and I might do that but just wanted to see other ways to create the rows on the fly.

Thanks,

Laurie

James K
Master Smack Fu Yak Hacker

3873 Posts

Posted - 2013-06-11 : 16:57:53
Here is one way you can do this:
DECLARE @startDate DATE = '20001001';
DECLARE @endDate DATE = '20131001';
;WITH cte AS
(
SELECT
YEAR(@startDate) AS FiscalYear,
@StartDate AS FiscalYearStart,
DATEADD(dd,-1,DATEADD(yy,1,@StartDate)) AS FiscalYearEnd
UNION ALL
SELECT
FiscalYear+1,
DATEADD(yy,1,FiscalYearStart),
DATEADD(yy,1,FiscalYearEnd)
FROM
cte
WHERE
FiscalYearEnd < @endDate
)
SELECT
FiscalYear,
CONVERT( CHAR(10),FiscalYearStart,101)
+ ' thru '
+ CONVERT( CHAR(10),FiscalYearEnd,101)
FROM cte ORDER BY FiscalYear;
Go to Top of Page
   

- Advertisement -