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
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)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With