Replace year in date date

I have a table with column ( dateDT), formatted as the date and time the variable ( @selYear) was input in my Select, formatted as int.

How can I replace the year in the date from my table with a variable input and return the result in the date and time format (within the selection)?

I tried the following, but this returns invalid dates / years:

CONVERT(DATETIME, (@selYear + MONTH(dateDT) + DAY(dateDT))) AS dateDT,

Example:

@selYear = 2014
dateDT = 2010-05-02 00:00:00.000

In this case, my result should be:

dateDT = 2014-05-02 00:00:00.000
+4
source share
3 answers

Solution using DATEADD :

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


SELECT DATEADD(YEAR,@selYear - YEAR(@dateDT),@dateDT)

This is an example with less than the current year:

DECLARE @selYear INT = 2009
DECLARE @dateDT DATETIME = '2010-05-02 00:00:00.000'


SELECT DATEADD(YEAR,@selYear - YEAR(@dateDT),@dateDT)
+5
source
SELECT REPLACE(dateDT, DATEPART(year, dateDT), @selYear)
+3
source

DATEFROMPARTS sqlserver 2012

DECLARE @selYear int = 2014
DECLARE @dateDT datetime = '2010-05-02'
SELECT DATEFROMPARTS(@selYear, 
                     DATEPART(m, @dateDT), 
                     DATEPART(d, @dateDT))
+3

Source: https://habr.com/ru/post/1538473/


All Articles