如何将这些日期值从varchar转换为datetime2?
WITH dates AS ( SELECT '6.7.2012' AS dtm UNION SELECT '13.2.2012' AS dtm UNION SELECT '3.12.2012' AS dtm UNION SELECT '20.11.2012' AS dtm ) SELECT CAST(dtm as datetime2) FROM dates ;
这会导致错误:
消息241,级别16,状态1,行6
转换从字符串转换日期和/或时间时失败.
Zohar Peled.. 9
使用try_convert
而不是cast
:
WITH dates AS ( SELECT '6.7.2012' AS dtm UNION SELECT '13.2.2012' AS dtm UNION SELECT '3.12.2012' AS dtm UNION SELECT '20.11.2012' AS dtm ) SELECT TRY_CONVERT(datetime2, dtm, 104) FROM dates ;
结果:
13.02.2012 00:00:00 20.11.2012 00:00:00 03.12.2012 00:00:00 06.07.2012 00:00:00
注意: try_convert是在2012版本中引入的,对于您需要使用的早期版本convert
,如果无法使用指定的样式转换varchar值,则存在异常.
使用try_convert
而不是cast
:
WITH dates AS ( SELECT '6.7.2012' AS dtm UNION SELECT '13.2.2012' AS dtm UNION SELECT '3.12.2012' AS dtm UNION SELECT '20.11.2012' AS dtm ) SELECT TRY_CONVERT(datetime2, dtm, 104) FROM dates ;
结果:
13.02.2012 00:00:00 20.11.2012 00:00:00 03.12.2012 00:00:00 06.07.2012 00:00:00
注意: try_convert是在2012版本中引入的,对于您需要使用的早期版本convert
,如果无法使用指定的样式转换varchar值,则存在异常.