简体   繁体   English

字符串到DateTime SQL转换

[英]String to DateTime SQL Conversion

I know this has been asked several times but I haven't seen it asked for my particular situation. 我知道这已被问了好几次,但我还没有看到它询问我的具体情况。

If a text was in this format: Dec 30 2006 12:38AM Is there any way to convert this to an actual datetime. 如果文本采用以下格式: 2006年12月30日12:38 AM有没有办法将其转换为实际日期时间。 I am not excited about creating a function to parse this to a date using substrings, etc. 我并不兴奋创建一个函数来使用子字符串等将其解析为日期。

A previous developer developed the whole application and decided to store all the date values in the database as a VARCHAR which conveniently changed them from something like: 2016-12-30 00:38:00 to Dec 30 2006 12:38AM . 之前的开发人员开发了整个应用程序,并决定将所有日期值存储在数据库中作为VARCHAR,可以方便地将它们从以下内容更改为: 2016-12-30 00:38:00Dec 30 2006 12:38AM This makes them non comareable (SMH) 这使得它们不可共处(SMH)

Just use cast() : 只需使用cast()

select cast('Dec 30 2006 12:38AM' as datetime)

Here is a SQL Fiddle. 是一个SQL小提琴。

--Please try this - 请试试这个

declare @var varchar(30) = 'Dec 30 2006 12:38AM' select convert(datetime, @var) 声明@var varchar(30)='Dec 30 2006 12:38 AM'选择转换(datetime,@ var)

Since you are converting strings (which is always risky), I would suggest try_convert() if 2012+. 由于您正在转换字符串(这总是有风险的),如果2012+,我会建议尝试try_convert()。 Try_Convert() will return a null if the conversion fails rather than throwing an error. 如果转换失败而不是抛出错误,Try_Convert()将返回null。

Example

Select ValidDate = try_convert(datetime,'Dec 30 2006 12:38AM')
      ,BogusDate = try_convert(datetime,'Not a Valid Date String')

Returns 返回

ValidDate                BogusDate
2006-12-30 00:38:00.000  NULL

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

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