I need to cast string values of the following formats to DateTime:
2042-04
2011-01
Is there an easy way to do this? I've tried CAST AND CONVERT without much luck.
Thanks!
declare @S varchar(7)
set @S = '2042-04'
select cast(stuff(@S, 5, 1, '')+'01' as datetime)
YYYYMMDD is a safe format regardless of SET DATEFORMAT. YYYY-MM-DD is not. http://www.sommarskog.se/wishlist.html#YYYYMMDD
Declare @Table Table
(
ColDateTime Varchar(100)
)
Insert into @Table
Select '2042-04' UNION ALL
Select '2011-01'
Select ColDateTime As VarcharCol,
Cast(
substring(ColDateTime,0,charindex('-',ColDateTime))+substring(ColDateTime,charindex('-',ColDateTime)+1,len(ColDateTime))+'01'
As DateTime) As DateTimeCol
from @Table