Question

I'm really not sure how to do the query I am looking for and was hoping someone could help me out. Basically I want exactly what this query below does, except to use them with a dynamic year so that I don't need to update the SPROC everytime the year changes;

   SELECT 
    case 
    when Convert(varchar(8), getDate(),1) between '01/01/2013' and '03/31/2013' then '04/01/2013 - 06/30/2013' 
    when Convert(varchar(8), getDate(),1) between '04/01/2013' and '06/30/2013' then '07/01/2013 - 09/30/2013'
    when Convert(varchar(8), getDate(),1) between '07/01/2013' and '09/30/2013' then '10/01/2013 - 12/31/2013'
    when Convert(varchar(8), getDate(),1) between '10/01/2013' and '12/31/2013' then '01/01/2014 - 03/31/2014'
    end

I want this to function like

when Convert(varchar(8), getDate(), 1) between '01/01/currentYear' and '03/31/currentYear' then '04/01/thisyear - 06/30/currentYear'

if anyone could give me a little help on this that would be great. Thank you very much, NickG

Was it helpful?

Solution

Pass in the year as a parameter:

DECLARE @YEAR VARCHAR(4)
SET @YEAR = DATEPART(YEAR,GETDATE())

SELECT 
    case 
    when Convert(varchar(8), getDate(),1) between '01/01/'+ @YEAR and '03/31/'+ @YEAR then '04/01/'+@YEAR+' - 06/30/'+@YEAR 
    when Convert(varchar(8), getDate(),1) between '04/01/'+ @YEAR and '06/30/'+ @YEAR then '07/01/'+@YEAR+' - 09/30/'+@YEAR
    when Convert(varchar(8), getDate(),1) between '07/01/'+ @YEAR and '09/30/'+ @YEAR then '10/01/'+@YEAR+' - 12/31/'+@YEAR
    when Convert(varchar(8), getDate(),1) between '10/01/'+ @YEAR and '12/31/'+ @YEAR then '01/01/'+@YEAR+' - 03/31/'+@YEAR
    end

OTHER TIPS

You can do this without using a CASE statement at all:

SELECT CONVERT(VARCHAR(8),(DATEADD(quarter, 1+DATEDIFF(quarter, 0, GETDATE()), 0)),1)+ ' - ' 
     + CONVERT(VARCHAR(8),(DATEADD(day,-1,DATEADD(quarter, 2+DATEDIFF(quarter, 0, GETDATE()), 0))),1)

To confirm it works on other dates:

DECLARE @date DATE = '2012-12-10'
SELECT CONVERT(VARCHAR(8),(DATEADD(quarter, 1+DATEDIFF(quarter, 0, @date), 0)),1)
        + ' - ' 
        + CONVERT(VARCHAR(8),(DATEADD(day,-1,DATEADD(quarter, 2+DATEDIFF(quarter, 0, @date), 0))),1)
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top