开发者

T-SQL String to DateTime-conversion

I need to cast string values of the following formats to DateTime:

2042-04
2011-01

Is there an e开发者_运维问答asy way to do this? I've tried CAST AND CONVERT without much luck.

Thanks!


try appending "-01" to the end of it and then doing the cast or convert


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


SELECT CAST('2011-01-01' AS DATETIME)
SELECT CONVERT(DATE , '2011-01-01')

It seems you need to add a 'day' to the string.


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
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜