Replace year in datetime date

前端 未结 3 1669
时光说笑
时光说笑 2021-01-13 00:21

I have a table with a column (dateDT), formatted as datetime and a variable input for the year (@selYear) in my Select, formatted as int.

相关标签:
3条回答
  • 2021-01-13 01:03

    You can use DATEFROMPARTS in sqlserver 2012

    DECLARE @selYear int = 2014
    DECLARE @dateDT datetime = '2010-05-02'
    SELECT DATEFROMPARTS(@selYear, 
                         DATEPART(m, @dateDT), 
                         DATEPART(d, @dateDT))
    
    0 讨论(0)
  • 2021-01-13 01:18

    A solution using DATEADD function:

    DECLARE @selYear VARCHAR(4) = 2014
    DECLARE @dateDT DATETIME = '2010-05-02 00:00:00.000'
    
    
    SELECT DATEADD(YEAR,@selYear - YEAR(@dateDT),@dateDT)
    

    This is example with smaller then current year:

    DECLARE @selYear INT = 2009
    DECLARE @dateDT DATETIME = '2010-05-02 00:00:00.000'
    
    
    SELECT DATEADD(YEAR,@selYear - YEAR(@dateDT),@dateDT)
    
    0 讨论(0)
  • 2021-01-13 01:18
    SELECT REPLACE(dateDT, DATEPART(year, dateDT), @selYear)
    
    0 讨论(0)
提交回复
热议问题