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.
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))
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)
SELECT REPLACE(dateDT, DATEPART(year, dateDT), @selYear)