[英]Converting a custom date string into SQL datetime2
I have to load a CSV file into a temp table in SQL server 2008. There is a column in the CSV file which contains a date string formatted like this 11/04/2017 at 08:24:52
. 我必须将CSV文件加载到SQL Server 2008中的临时表中。CSV文件中有一列,其中包含日期字符串,其格式如下: 11/04/2017 at 08:24:52
。 How can I parse this string and insert it into a datetime2
column? 如何解析此字符串并将其插入datetime2
列?
The following results in expected conversion error - Conversion failed when converting date and/or time from character string.
以下结果导致预期的转换错误- 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')
You can use stuff
to remove the at
and convert
using style 103 (assuming dd/mm/yyyy
) or 101 (assuming mm/dd/yyyy
): 可以使用stuff
,以除去at
与convert
使用样式103(假设dd/mm/yyyy
)或101(假设mm/dd/yyyy
):
DECLARE @Date varchar(30) = '11/04/2017 at 08:24:52'
SELECT CONVERT(datetime2, STUFF(@Date, 12, 3, ''), 103)
Result: 结果:
11.04.2017 08:24:52
You just need to remove the at
along with one of the spaces and then tell SQL Server which format you have your days and months in: 您只需要删除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
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.