Sql将'dd-mm yyyy'投射到日期时间

时间:2015-03-09 18:53:38

标签: sql-server datetime

我有两张桌子

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

'17-JUL-14'

中有temp等值

我想从info表中插入temp表。

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

1 个答案:

答案 0 :(得分: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