将Varchar列转换为日期时间格式 - SQL Server [英] Convert Varchar Column to Datetime format - SQL Server

查看:669
本文介绍了将Varchar列转换为日期时间格式 - SQL Server的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个从CSV导入的数据表,如下所示:

I have a table of data imported from CSV as follows:

FirstTimeTaken      LatestTimeTaken     Market                  Outcome         Odds    NumberOfBets    VolumeMatched   InPlay
03/08/2013 15:30:14 03/08/2013 15:32:28 Over/Under 3.5 Goals    Over 3.5 Goals  5       10              118             1
03/08/2013 14:26:40 03/08/2013 14:29:43 Correct Score           0 - 0           7       12              279             1
03/08/2013 15:15:34 03/08/2013 15:27:39 Match Odds              Barnsley        110     7               9               1
28/07/2013 16:57:26 29/07/2013 21:35:55 Match Odds              Barnsley        3       9               35              0

我不得不以varchar格式导入前两列,因为我正在尝试导入为datetime的错误。现在我有一个表中的数据,我需要将列格式从Varchar转换为日期时间。我试过:

I had to import the first 2 columns in varchar format because I was getting errors trying to import as datetime. Now I have the data in a table, I need to convert the Column format from Varchar to Datetime. I tried:

ALTER TABLE #CSVTest_Data
ALTER COLUMN FirstTimeTaken DATETIME
ALTER TABLE #CSVTest_Data
ALTER COLUMN LatestTimeTaken DATETIME

这导致错误:'将varchar数据类型转换为datetime数据类型导致超出范围值'。
我知道删除最后一行数据可以摆脱这个问题,所以我怀疑系统认为日期格式是MM / DD / YYYY,而实际上是DD / MM / YYYY。
以下查询工作正常:

This results in error: 'The conversion of a varchar data type to a datetime data type resulted in an out-of-range value'. I know that removing the last row of data gets rid of the problem, so I suspect that the system thinks the date format is MM/DD/YYYY whereas it is actually DD/MM/YYYY. The following query works fine:

SELECT convert(VARCHAR(50),FirstTimeTaken,105) from #CSVTest_Data 
SELECT convert(VARCHAR(50),LatestTimeTaken,105) from #CSVTest_Data

选择转换(VARCHAR(50),LatestTimeTaken,105)不将列格式转换为datetime。我会感谢一些帮助,如何做到这一点。谢谢。

But this does not convert the column format to datetime. I would appreciate some help on how to do this. Thanks.

推荐答案

尝试使用 SET DATEFORMAT

SET DATEFORMAT dmy

这篇关于将Varchar列转换为日期时间格式 - SQL Server的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆