简体   繁体   English

在sql中将varchar转换为日期时间

[英]converting varchar to datetime in sql

currently in my DB i have目前在我的数据库中我有

20181015 151706 ---------- varchar(15)
2018-10-15 15:17:06 000--- Datetime

how do i convert this from varchar to datetime ?我如何将它从 varchar 转换为 datetime?

i have tried using this command below我试过在下面使用这个命令

SELECT CONVERT(Datetime,CREATE_TIME , 120) from TABLE

but im getting error但我收到错误

"The conversion of a varchar data type to a datetime data type resulted in an out-of-range value." “将 varchar 数据类型转换为 datetime 数据类型导致值超出范围。”

SELECT CONVERT(Datetime,CREATE_TIME , 120) from TABLE

The error caused by your special 20181015 151706 varchar DateTime value,由您的特殊20181015 151706 varchar DateTime 值引起的错误,

you can try to use substring function make the DateTime format string value then do convert .您可以尝试使用substring函数制作 DateTime 格式的字符串值,然后进行convert

SELECT CONVERT(DATETIME,CONCAT(substring(col, 1, 4),'-',substring(col, 5, 2),'-',substring(col, 7, 2),' ',substring(col, 9, 2),':',substring(col, 11, 2),':',substring(col, 13, 2)))
FROM (
   select REPLACE('20181015 151706',' ','') col
) t1

sqlfiddle sqlfiddle

There's a little issue with your date string.你的日期字符串有点问题。 It works when 20181015 151706 is changed to just the date part 20181015 .20181015 151706更改为仅日期部分20181015时,它会起作用。

SELECT CONVERT(DATETIME, col)
FROM (
   select '20181015' col
) t1

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

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