Updating year in datetime variable

爷,独闯天下 提交于 2019-12-10 13:08:03

问题


I'm playing around with manipulating a datetime variable. I can't seem to find a way to update a datetime variable year to the current year.

For example I have

2007-12-01 00:00:00.000

But I would like that to be

2012-12-01 00:00:00.000    (The current year were in)

I've been playing with datediff, but I can't seem to nail it.

Any advice would be appreciated.

Thanks


回答1:


DECLARE @date datetime = '2007-01-09T12:34:56'
SELECT @date = DATEADD(yyyy, DATEDIFF(yyyy, @date, GETDATE()), @date)

SELECT @date



回答2:


Maybe something like this:

For sql server 2008+

DECLARE @date DATETIME='2007-12-01 00:00:00.000'
SET @date=DATEADD(year,DATEDIFF(year,@date,GETDATE()),@date)

For sql server 2005

DECLARE @date DATETIME
SET @date='2007-12-01 00:00:00.000'
SET @date=DATEADD(year,DATEDIFF(year,@date,GETDATE()),@date)



回答3:


Here's a simple way:

select @yourDate = dateadd(year, datepart(year, getdate()) - datepart(year, @yourDate), @yourDate)


来源:https://stackoverflow.com/questions/10550368/updating-year-in-datetime-variable

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!