Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Replace year in datetime date

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.

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

I have tried the following but this returns wrong 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
like image 793
Mike Avatar asked Apr 28 '14 19:04

Mike


1 Answers

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)
like image 174
gotqn Avatar answered Sep 20 '22 10:09

gotqn