简体   繁体   中英

SQL Server 2008 R2: Updating past dates to the 'next' date

I'm using SQL Server 2008 R2. I have a table with lots of dates, some in the past, some in the future. What I would like to do would be to update them so the dates are the 'next' date, relative to today.

For example given the current date is '2014-02-09'

Current Value     Desired Value
-------------------------------------------------    
'2010-01-06'      '2015-01-06' (Updated to 2015)
'2008-03-28'      '2014-03-28' (Updated to 2014)

I'd need to account for dates on 29th of Feb, just to make this easier!

What is the best way to do this?

You can determine who many years in the past the date is. Then add that number of years plus one to the date:

update t
    set datecol = dateadd(year,
                          datediff(year, datecol, getdate()) + 1,
                          datecol)
    where datecol < getdate();

This should work:

Declare @CurrentDate datetime
SET @CurrentDate = '2014-02-09'

;WITH NewDatesThisYear AS
(
    SELECT [Date], 
           NewDate = DateAdd(yy, YEAR(@CurrentDate)-1900,  
                     DateAdd(m,  MONTH([Date]) - 1, DAY([Date]) - 1)) 
    FROM dbo.Dates
)
, NewDates AS
(
    SELECT [Date], 
           NewDate = CASE WHEN NewDate < @CurrentDate 
                     THEN DateAdd(yy, 1,NewDate) 
                     ELSE NewDate END
    FROM NewDatesThisYear
)
UPDATE NewDates SET [Date] = NewDate
WHERE [Date] < @CurrentDate

Demo

untested:

CASE WHEN dateadd(yy, datecol, datediff(yy, datecol, getdate())) > getdate()
     THEN dateadd(yy, datecol, datediff(yy, datecol, getdate()))
     ELSE dateadd(yy, datecol, datediff(yy, datecol, getdate())+1)
END

This would be so much easier if SQL Server supported a simple age calculation :-)

dateadd(yy, datecol, age(datecol, getdate()) +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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM