【问题标题】:Varchar to Date - Conversion failed when converting date and/or time from character stringVarchar to Date - 从字符串转换日期和/或时间时转换失败
【发布时间】:2018-02-21 00:00:55
【问题描述】:

我正在尝试使用批量插入加载 csv 文件。我的 csv 文件有 4 个日期列,我认为这是导致问题的原因。日期格式为DD/MM/YY,如何将其更改为DD/MM/YYYY。我需要将这些日期字段导入date 列而不是varchar

我正在将此文件加载到 #temptable 中,然后使用以下代码将其插入到数据库表中:

insert into table (a,b,c,d,e)

select a, 
       b,
       convert(date,c,103),
       convert(date,d,103),
       e
from #temptable

不知道我哪里出错了。任何帮助将不胜感激。

【问题讨论】:

  • 临时表中的c列,是输入日期还是varchar?
  • 是的,我的 temptable 中的所有列都是 varchar,因为当我尝试使用批量插入并将其直接加载到带有日期列的表中时,它给了我:批量加载数据转换错误(类型不匹配或无效字符对于指定的代码页。这就是为什么我用 Varchar 将其加载到表中,然后使用 convert() 插入到实际表中

标签: sql sql-server csv bulkinsert


【解决方案1】:

您可以使用 SET DATEFORMAT

示例

Set DateFormat DMY
Declare @D varchar(25) = '20/02/2018'

Select try_convert(date,@D)

退货

2018-02-20

编辑 - 只是为了好玩

如果将 DateFormat 设置为 MDY,try_convert 将返回 null

Set DateFormat MDY
Declare @D varchar(25) = '20/02/2018'

Select try_convert(date,@D)

退货

NULL

【讨论】:

    【解决方案2】:

    如果临时表中的格式“改变”,那是因为它们已经是日期。你也许可以这样做:

    insert into table (a, b, c, d, e)
        select a, b, c, d, e
        from #temptable;
    

    如果这不起作用,请找出有问题的值:

    select d, e
    from #temptable
    where convert(date, c, 103) is null or
          convert(date, d, 103) is null;
    

    【讨论】:

      猜你喜欢
      • 2020-04-15
      • 2012-04-17
      • 2017-12-07
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多