简体   繁体   English

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

[英]How to convert dates from varchar to datetime2 in SQL Server?

How can I convert these kind of date values from varchar to datetime2? 如何将这类日期值从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
;

This results in an error: 这会导致错误:

Msg 241, Level 16, State 1, Line 6 消息241,第16级,状态1,第6行
Conversion failed when converting date and/or time from character string. 从字符串转换日期和/或时间时转换失败。

Use try_convert instead of cast : 使用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
;

Results: 结果:

13.02.2012 00:00:00
20.11.2012 00:00:00
03.12.2012 00:00:00
06.07.2012 00:00:00

Note: try_convert was introduced in 2012 version, for earlier versions you need to use convert , risking an exception if the varchar value can't be converted using the specified style. 注意: try_convert是在2012年版本中引入的,对于较早的版本,您需要使用convert ,如果无法使用指定的样式转换varchar值,则可能会发生异常。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM