简体   繁体   English

T-SQL 字符串到日期时间的转换

[英]T-SQL String to DateTime-conversion

I need to cast string values of the following formats to DateTime:我需要将以下格式的字符串值转换为 DateTime:

2042-04
2011-01

Is there an easy way to do this?是否有捷径可寻? I've tried CAST AND CONVERT without much luck.我试过CAST AND CONVERT没有太多运气。

Thanks!谢谢!

try appending "-01" to the end of it and then doing the cast or convert尝试将“-01”附加到它的末尾,然后进行强制转换或转换

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 . YYYYMMDD 是一种安全格式,与SET DATEFORMAT无关。 YYYY-MM-DD is not. YYYY-MM-DD 不是。 http://www.sommarskog.se/wishlist.html#YYYYMMDD 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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM