In T-SQL, how do i look at the date in a column and select just the mm/dd and give it this years date or next years date?

StackOverflow https://stackoverflow.com/questions/22571440

Question

SQL 2008R2 using a SQL 2005db.

Here is what I have for a table

Date1             Date2             
02/01/2007        NULL             
08/15/2009        NULL              
12/15/2014        NULL             

Here is what I am expecting. DATE2 is used to set the annual appraisal date based on the month/day they signed up. Basically, if the signup date is in the past, the year should be 2014. If signup date is this year, then appraisal date should be next year, and so on and so on for the coming years.

SignUpDate        AppraisalDate           
02/01/2007        02/01/2014        
08/15/2009        08/15/2014
02/20/2014        02/20/**2015**
12/15/2014        12/15/**2015**  

Here is an example of the statement I am using. However, I cannot get the last date in AppraisalDate column to rollover to the next year. I'm getting SignUpDate from a temp table. I left out the join stuff for clarity.

select 
SignUpDate = TempTable.Date1, 
AppraisalDate = dateadd(YEAR, year(getdate())-year(TempTable.Date1), TempTable.Date1)  

That's about it. I posted the first part of this question a couple of weeks ago and got this part down (it helped tremendously). However, I just cant get the date to roll over.

Thanks for helping!

Was it helpful?

Solution

You can use a CASE statement to do this:

SELECT
SignUpDate = TempTable.Date1,
AppraisalDate = 
  CASE WHEN (year(Date1) = year(getdate()))
  THEN 
    dateadd(YEAR, 1, TempTable.Date1)
  ELSE
    dateadd(YEAR, year(getdate())-year(TempTable.Date1), TempTable.Date1)
  END
FROM TempTable

Sample SQL Fiddle

Results:

|                      SIGNUPDATE |                   APPRAISALDATE |
|---------------------------------|---------------------------------|
| February, 01 2007 01:00:00+0000 | February, 01 2014 01:00:00+0000 |
|   August, 15 2009 02:00:00+0000 |   August, 15 2014 02:00:00+0000 |
| December, 15 2014 01:00:00+0000 | December, 15 2015 01:00:00+0000 |

OTHER TIPS

Try this

select SignUpDate, 
case when Year(SignUpDate) < Year(getdate()) Then  DATEADD (year,Year(getdate()) - Year(SignUpDate),SignUpDate)
when Year(SignUpDate) =  Year(getdate()) then DATEADD (year,1,SignUpDate) end as AppraisalDate
from Appraisal;
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top