Creating date in SQL Server 2008

Jaiesh_bhai picture Jaiesh_bhai · Oct 22, 2013 · Viewed 63.4k times · Source

Is there something similar to DATEFROMPARTS(year, month, day) in SQL Server 2008? I want to create a date using the current year and month, but my own day of the month. This needs to be done in one line in order to be used in a computed column formula.

For Example (I'm not sure if it works because I do not have SQL Server 2012):

DATEFROMPARTS(YEAR(GETDATE()), MONTH(GETDATE()), 3)

Is there a way to do this in SQL Server 2008?

DATEFROMPARTS Seems only available in SQL Server 2012 (link)

Answer

Ken Richards picture Ken Richards · Oct 22, 2013

You could use something like this to make your own datetime:

DECLARE @year INT = 2012
DECLARE @month INT = 12
DECLARE @day INT = 25

SELECT CAST(CONVERT(VARCHAR, @year) + '-' + CONVERT(VARCHAR, @month) + '-' + CONVERT(VARCHAR, @day)
 AS DATETIME)