我想转换一个像这样的字符串:

'10/15/2008 10:06:32 PM'

转换为Sql Server中的DATETIME值。

在甲骨文,我会这样说:

TO_DATE('10/15/2008 10:06:32 PM','MM/DD/YYYY HH:MI:SS AM')

这个问题意味着我必须将字符串解析为一种标准格式,然后使用其中一种代码进行转换。对于这样一个平凡的行动来说,这似乎很荒谬。有没有更简单的方法?


当前回答

试试这个

Cast('7/7/2011' as datetime)

and

Convert(DATETIME, '7/7/2011', 101)

有关详细信息,请参阅CAST和CONVERT (Transact-SQL)。

其他回答

好评最多的答案是guravg和Taptronic的。然而,有一件事我想做。

它们显示的从0到131的具体格式数字可能会根据您的用例而有所不同(请参阅此处的完整数字列表),输入数字可能是不确定的,这意味着预期的结果日期在一个SQL SERVER实例到另一个实例之间是不一致的,出于同样的原因避免使用转换为字符串的方法。

从SQL Server 2005开始,其兼容性级别为90, 隐式日期转换变得不确定。日期转换 开始依赖于SET LANGUAGE和SET DATEFORMAT 90级。

非确定性值为0-100、106、107、109、113、130。这可能会导致错误。


最好的选择是坚持一个确定性的设置,我目前的首选是ISO格式(12、112、23、126),因为它们似乎是IT人员用例的最标准。

Convert(varchar(30), '210510', 12)                   -- yymmdd
Convert(varchar(30), '20210510', 112)                -- yyyymmdd
Convert(varchar(30), '2021-05-10', 23)               -- yyyy-mm-dd
Convert(varchar(30), '2021-05-10T17:01:33.777', 126) -- yyyy-mm-ddThh:mi:ss.mmm (no spaces)

If you want SQL Server to try and figure it out, just use CAST CAST('whatever' AS datetime) However that is a bad idea in general. There are issues with international dates that would come up. So as you've found, to avoid those issues, you want to use the ODBC canonical format of the date. That is format number 120, 20 is the format for just two digit years. I don't think SQL Server has a built-in function that allows you to provide a user given format. You can write your own and might even find one if you search online.

简短的回答:

SELECT convert(date, '10/15/2011 00:00:00', 101) as [MM/dd/YYYY]

其他日期格式可以在SQL Server Helper > SQL Server日期格式中找到

本页包含CONVERT函数可用的所有指定日期时间转换的一些引用。如果您的值不属于可接受的模式之一,那么我认为最好的方法是采用ParseExact路线。

就个人而言,如果您正在处理任意的或完全不符合要求的格式,只要您事先知道它们是什么或将要是什么,那么只需使用regexp来提取您想要的日期部分,并形成有效的date/datetime组件。