如何使用批量插入 csv 到日期时间格式正确的 sql 服务器?

How use Bulk insert csv to sql server with datetime format correct?

我想使用批量插入文件 csv 插入到 SQL Server 2012。同一列有日期时间,但使用批量插入日期时间格式不起作用,我不使用 SSIS

示例创建 Table

CREATE TABLE [dbo].[scanindex_test](
    [request_no] [varchar](13) NOT NULL,
    [request_date] [datetime] NULL,
    [id_card] [varchar](20) NULL,
    [firstname] [varchar](100) NULL,
    [surname] [varchar](100) NULL
)

查询 Sql 服务器 2012:

declare 
    @path      varchar(255),
    @sql       varchar(5000)           

SET @path = 'C:\Test\TESTFILE.csv'    

set @sql = 'BULK INSERT [dbo].[scanindex_test] FROM ''' + @path + ''' 
      ' + '     WITH (      
                CODEPAGE=''RAW'',           
                FIELDTERMINATOR = '','', 
                ROWTERMINATOR = ''\n''
                ) '
print @sql
exec (@sql)

当我运行查询时出现错误:

Msg 4864, Level 16, State 1, Line 1
Bulk load data conversion error (type mismatch or invalid character for the specified codepage) for row 11, column 2 (request_date).
Msg 4865, Level 16, State 1, Line 1
Cannot bulk load because the maximum number of errors (10) was exceeded.
Msg 7399, Level 16, State 1, Line 1
The OLE DB provider "BULK" for linked server "(null)" reported an error. The provider did not give any information about the error.
Msg 7330, Level 16, State 2, Line 1
Cannot fetch a row from OLE DB provider "BULK" for linked server "(null)".

CSV 文件中的示例数据

request_no | request_date  | id_card  | firstname    | surname
1          | 12/7/2017     | 1122     | AA           | BB
2          | 12/7/2017     | 4399     | SS           | EE
3          | 13/7/2017     | 5599     | QQ           | KK     

运行查询结果:

request_no | request_date            | id_card  | firstname | surname
1          | 2017-12-07 00:00:00.000 | 1122     | AA        | BB
2          | 2017-12-07 00:00:00.000 | 4399     | SS        | EE
3  >> Error, because it's look datetime format: 2017-13-07 (yyyy-mm-dd)

但我希望结果日期时间格式 (YYYY-MM-DD) 正确:

request_no | request_date            | id_card | firstname | surname
1          | 2017-07-12 00:00:00.000 | 1122    | AA        | BB
2          | 2017-07-12 00:00:00.000 | 4399    | SS        | EE
3          | 2017-07-13 00:00:00.000 | 5599    | QQ        | KK

请帮助我。提前致谢 ;)

您需要将 DATEFORMAT 更改为 DMY。将以下内容添加到脚本的顶部应该有效:

SET DATEFORMAT DMY;

所以你的完整脚本应该是:

SET DATEFORMAT DMY;

declare 
    @path      varchar(255),
    @sql       varchar(5000)           

SET @path = 'C:\Test\TESTFILE.csv'    

set @sql = 'BULK INSERT [dbo].[scanindex_test] FROM ''' + @path + ''' 
      ' + '     WITH (      
                CODEPAGE=''RAW'',           
                FIELDTERMINATOR = '','', 
                ROWTERMINATOR = ''\n''
                ) '
print @sql
exec (@sql)

它适用于批量插入:

SET DATEFORMAT DMY
BULK INSERT [dbo].[TRX]
        FROM 'C:\..\trx2.txt'
            WITH
    (           
                FIELDTERMINATOR = '\t',
                ROWTERMINATOR = '\n',
                FIRSTROW = 2
    )
PRINT 'BULK INSERT [TRX2]'
GO