【问题标题】:Sql cast 'dd-mmm-yyy' to datetimeSql 将 'dd-mm yyyy' 转换为日期时间
【发布时间】:2015-03-09 18:53:37
【问题描述】:

我有两张桌子

  • temp 表中我有[infoDate] [nvarchar](255) NULL
  • info 表中我有[infoDate] [datetime] NULL

temp 表中有 '17-JUL-14' 之类的值

我想从temp 表中插入info 表。

insert into info (infoDate) 
   select (infoDate) 
   from temp

我尝试了以下查询,但无法将字符串转换为日期时间

select convert(varchar, '17-JUL-14', 105)

SELECT REPLACE(CONVERT(VARCHAR,'17-JUL-14',6),'-',' ')

SELECT SUBSTRING('17-JUL-14',1,2)+' '+SUBSTRING('17-JUL-14',4,3)+' '+SUBSTRING('17-JUL-14',8,2)

这个查询有效

SELECT CONVERT(datetime,SUBSTRING('17-JUL-14',1,2)+' '+SUBSTRING('17-JUL-14',4,3)+' '+SUBSTRING('17-JUL-14',8,2),106)

但是现在,如何插入info 表?

 insert into info (infoDate) 
    select 
       (CONVERT(datetime, SUBSTRING(infoDate, 1, 2) + ' ' + 
                          SUBSTRING(infoDate, 4, 3) + ' ' + 
                          SUBSTRING(infoDate, 8, 2), 106)) 
    from temp

【问题讨论】:

  • 您当前的插入查询有什么问题
  • 只需执行 SELECT CONVERT(DATETIME, '17-JUL-14') 这应该将其转换为日期时间
  • 尝试时会发生什么?你有错误吗?
  • 我收到此错误“从字符串转换日期和/或时间时转换失败。”

标签: sql-server datetime


【解决方案1】:

让我们简化代码。

之前

insert into info (infoDate) 
    select 
       (CONVERT(datetime, SUBSTRING(infoDate, 1, 2) + ' ' + 
                          SUBSTRING(infoDate, 4, 3) + ' ' + 
                          SUBSTRING(infoDate, 8, 2), 106)) 
    from temp

之后

insert into info (infoDate) 
    select 
       (CONVERT(datetime2, infoDate, 106))
    from temp

【讨论】:

  • 它不起作用,我收到“从字符串转换日期和/或时间时转换失败。”错误
  • 请务必确认您正在使用临时表中的非损坏数据。这可能是问题的根源。
猜你喜欢
  • 2013-10-19
  • 1970-01-01
  • 2020-06-22
  • 1970-01-01
  • 2023-03-15
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多