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

'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')

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


当前回答

dateadd(day,0,'10/15/2008 10:06:32 PM')

其他回答

好评最多的答案是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)

在MSSQL中隐式转换字符串到日期时间

create table tmp 
(
  ENTRYDATETIME datetime
);

insert into tmp (ENTRYDATETIME) values (getdate());
insert into tmp (ENTRYDATETIME) values ('20190101');  --convert string 'yyyymmdd' to datetime


select * from tmp where ENTRYDATETIME > '20190925'  --yyyymmdd 
select * from tmp where ENTRYDATETIME > '20190925 12:11:09.555'--yyyymmdd HH:MIN:SS:MS



这段代码解决了我的问题:

convert(date,YOUR_DATE,104)

如果你使用时间戳,你可以你下面的代码:

convert(datetime,YOUR_DATE,104)

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.

dateadd(day,0,'10/15/2008 10:06:32 PM')