如何在SQL Server中将日期从varchar转换为datetime2?

时间:2017-01-19 11:10:40

标签: sql sql-server date sql-server-2016

如何将这些日期值从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
;

这会导致错误:

  

Msg 241,Level 16,State 1,Line 6
  从字符串转换日期和/或时间时转换失败。

1 个答案:

答案 0 :(得分: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值,则存在异常风险