我想转换一个像这样的字符串:
'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')
这个问题意味着我必须将字符串解析为一种标准格式,然后使用其中一种代码进行转换。对于这样一个平凡的行动来说,这似乎很荒谬。有没有更简单的方法?
我想转换一个像这样的字符串:
'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)。
其他回答
试试这个
Cast('7/7/2011' as datetime)
and
Convert(DATETIME, '7/7/2011', 101)
有关详细信息,请参阅CAST和CONVERT (Transact-SQL)。
对于这个问题,我使用的最好的解决方案是在Sql Server 2005中有一个使用DateTime的CLR函数。Parse或ParseExact函数返回指定格式的DateTime值。
简短的回答:
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.
就个人而言,如果您正在处理任意的或完全不符合要求的格式,只要您事先知道它们是什么或将要是什么,那么只需使用regexp来提取您想要的日期部分,并形成有效的date/datetime组件。