Replace year in datetime date

前端 未结 3 1688
时光说笑
时光说笑 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条回答
  •  旧时难觅i
    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)
    

提交回复
热议问题