SQL Server Forums
Profile | Register | Active Topics | Members | Search | Forum FAQ
 
Register Now and get your question answered!
Username:
Password:
Save Password
Forgot your Password?

 All Forums
 SQL Server 2008 Forums
 Transact-SQL (2008)
 Is there a cleaner way to do this?
 New Topic  Reply to Topic
 Printer Friendly
Author Previous Topic Topic Next Topic  

LaurieCox
Posting Yak Master

USA
149 Posts

Posted - 06/11/2013 :  15:52:24  Show Profile  Reply with Quote
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
Flowing Fount of Yak Knowledge

3704 Posts

Posted - 06/11/2013 :  16:57:53  Show Profile  Reply with Quote
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
  Previous Topic Topic Next Topic  
 New Topic  Reply to Topic
 Printer Friendly
Jump To:
SQL Server Forums © 2000-2009 SQLTeam Publishing, LLC Go To Top Of Page
This page was generated in 0.06 seconds. Powered By: Snitz Forums 2000