2017-05-29 21 views
0

在我的.net winform应用程序中,我将excel数据导入到SQL服务器。在我的Excel表中,我有'STRT_TM'列,其中包含03/01/2017 21:33:22格式的日期。我想做显式转换,因为在隐式转换中,convert函数无法确定日期是dd/mm/yyyy还是mm/dd/yyyy。将字符串列转换为DataTime

在Sql Server中,我试图将字符串转换为日期。这里是代码

select convert(smalldateTime,SUBSTRING('03/01/2017 14:05:34',7,4)+ 
SUBSTRING('03/01/2017 14:05:34',1,2) + SUBSTRING('03/01/2017 14:05:34',4,2)) 

结果是2017年3月1日00:00:00 但是当我尝试包括一部分时间提示错误。 这里是代码。

select convert(smalldateTime,SUBSTRING('03/01/2017 14:05:34',7,4)+ 
SUBSTRING('03/01/2017 14:05:34',1,2) + SUBSTRING('03/01/2017 14:05:34',4,2) + 
Substring('03/01/2017 14:05:34',12,8)) 

和错误是

Msg 295, Level 16, State 3, Line 3 
Conversion failed when converting character string to smalldatetime data type. 

任何帮助将不胜感激。

回答

1

你错过了日期和时间之间的空间:

select convert(smalldateTime, 
Substring('03/01/2017 14:05:34',7,4) + 
Substring('03/01/2017 14:05:34',1,2) + 
Substring('03/01/2017 14:05:34',4,2) + ' ' + 
Substring('03/01/2017 14:05:34',12,8))