Sql server 如何根据条件在sqlserver中仅更新datetime之后的年份 在我的数据库中 波迪特

Sql server 如何根据条件在sqlserver中仅更新datetime之后的年份 在我的数据库中 波迪特,sql-server,Sql Server,我需要更新今年大于2015年的数据,因为2015年可以轻松解决此问题: UPDATE UnnamedTable SET PoDate = DATEADD(year, DATEDIFF(year,PoDate,'20150101'), PoDate) WHERE PoDate >= '20160101' 其逻辑是,应从日期中减去2015年日期与未来日期之


我需要更新今年大于2015年的数据,因为2015年可以轻松解决此问题:

UPDATE UnnamedTable SET PoDate = DATEADD(year,
                                    DATEDIFF(year,PoDate,'20150101'),
                                 PoDate)
WHERE PoDate >= '20160101'

其逻辑是,应从日期中减去2015年日期与未来日期之间的(整)年差。通过将参数交换到
DATEDIFF
,使后面的日期先到,我不需要显式的
-
来否定该值。

DATEADD
/
DATEDIFF
可以轻松解决此问题:

UPDATE UnnamedTable SET PoDate = DATEADD(year,
                                    DATEDIFF(year,PoDate,'20150101'),
                                 PoDate)
WHERE PoDate >= '20160101'
update tab
set date_col = DATEFROMPARTS ( 2015, datepart(mm,date_col), datepart(dd,date_col))
where datepart(year,date_col) > 2015
其逻辑是,应从日期中减去2015年日期与未来日期之间的(整)年差。通过将参数交换为
DATEDIFF
,使后面的日期先到,我不需要显式的
-
来否定该值

update tab
set date_col = DATEFROMPARTS ( 2015, datepart(mm,date_col), datepart(dd,date_col))
where datepart(year,date_col) > 2015
试试这个

Select '2015-12-01 00:00:00.000' as date_col
into #temp
union 
Select '2016-12-01 00:00:00.000'
union
Select '2017-12-01 00:00:00.000'
union 
Select '2018-12-01 00:00:00.000'
union
Select '2019-12-01 00:00:00.000'

update #temp
set date_col = dateadd(yyyy,datediff(yyyy,date_col,'2015-01-01'),date_col) 
from #temp
试试这个

Select '2015-12-01 00:00:00.000' as date_col
into #temp
union 
Select '2016-12-01 00:00:00.000'
union
Select '2017-12-01 00:00:00.000'
union 
Select '2018-12-01 00:00:00.000'
union
Select '2019-12-01 00:00:00.000'

update #temp
set date_col = dateadd(yyyy,datediff(yyyy,date_col,'2015-01-01'),date_col) 
from #temp