I am trying to convert a date with individual parts such as 12, 1, 2007 into a datetime in SQL Server 2005. I have tried the following:
CAST(DATEPART(year, DATE)+'-'+ DATEPART(month, DATE) +'-'+ DATEPART(day, DATE) AS DATETIME)
but this results in the wrong date. What is the correct way to turn the three date values into a proper datetime format.
Try this query:
Result:
Sql Server 2012 has a function that will create the date based on the parts (DATEFROMPARTS). For the rest of us, here is a db function I created that will determine the date from the parts (thanks @Charles)...
You can call it like this...
Returns...
Try CONVERT instead of CAST.
CONVERT allows a third parameter indicating the date format.
List of formats is here: http://msdn.microsoft.com/en-us/library/ms187928.aspx
Update after another answer has been selected as the "correct" answer:
I don't really understand why an answer is selected that clearly depends on the NLS settings on your server, without indicating this restriction.
It is safer and neater to use an explicit starting point '19000101'
I add a one-line solution if you need a datetime from both date and time parts:
If you don't want to keep strings out of it, this works as well (Put it into a function):