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

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

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


当前回答

在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



其他回答

SQL Server(2005, 2000, 7.0)没有任何灵活的,甚至是不灵活的方法来获取任意结构的字符串格式的datetime并将其转换为datetime数据类型。

所谓“随意”,我指的是“一种写作者(虽然可能不是你、我或地球另一边的人)认为是直观和完全明显的形式。”坦率地说,我不确定是否有这样的算法。

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

我花了一分钟才弄明白,所以在这里它可能会帮助到别人:

在SQL Server 2012和更好的版本中,你可以使用这个函数:

SELECT DATEFROMPARTS(2013, 8, 19);

下面是我如何将日期的部分提取到这个函数中:

select
DATEFROMPARTS(right(cms.projectedInstallDate,4),left(cms.ProjectedInstallDate,2),right( left(cms.ProjectedInstallDate,5),2)) as 'dateFromParts'
from MyTable

简短的回答:

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

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

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.