2017-06-06 71 views
0

我必須將CSV文件加載到SQL Server 2008中的臨時表中。在CSV文件中有一列包含格式如下的日期字符串11/04/2017 at 08:24:52。我如何解析此字符串並將其插入到datetime2列中?將自定義日期字符串轉換爲SQL datetime2

在預期的轉換錯誤的結果如下 - Conversion failed when converting date and/or time from character string.

create table #temp 
    (
    date_col datetime2(2), 
    some_id varchar(20) 
) 

    insert into #temp(date_col , some_id) 
    values ('11/04/2017 at 08:24:52', '2323434') 

回答

1

你只需要刪除at與空間的一個沿,然後告訴你,有你的日子和月份以何種格式的SQL Server:

select convert(datetime2, replace('11/04/2017 at 08:24:52',' at',''),103) -- 2017-04-11 08:24:52.0000000 
     ,convert(datetime2, replace('11/04/2017 at 08:24:52',' at',''),101) -- 2017-11-04 08:24:52.0000000 
+0

謝謝,更換似乎更優雅對我來說比的東西,所以我會接受你的答案。 –

1

可以使用stuff以除去at和使用樣式103(假設dd/mm/yyyy)或101(假設mm/dd/yyyyconvert

DECLARE @Date varchar(30) = '11/04/2017 at 08:24:52' 

SELECT CONVERT(datetime2, STUFF(@Date, 12, 3, ''), 103) 

結果:

11.04.2017 08:24:52