使用批量插入时如何 trim 空格?

How to trim spaces when using a bulk insert?

我正在使用批量插入导入 rpt 文件,但出现了这些错误:

Msg 4866, Level 16, State 1, Line 1
The bulk load failed. The column is too long in the data file for row 1, column 1. Verify that the field terminator and row terminator are specified correctly.

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)".

我认为这是由于文件列之间的空格造成的,有什么办法可以 trim 这些空格吗?

谢谢!

如果你的文件只有spaces,你的文件格式是固定的,你需要一个格式文件来加载它。

SELECT *
  FROM  OPENROWSET(BULK  'C:\Users\Admin\Desktop\Extractions\F0005.rpt',
  FORMATFILE='C:\myTestSkipField.fmt'  
   ) AS t1;

我在下面包含了一个示例 .fmt 文件,使用 EmptyField 列映射文件中的前几个字段以映射 space。你可以省略这个,因为看起来你无论如何都必须 trim 你的字段使用 LTRIM(TRIM([column]))

9.0
8
1     SQLCHAR     0     4     ""      1     DRSY        SQL_Latin1_General_CP1_CI_AS
2     SQLCHAR     0     1     ""      2     Empty1      SQL_Latin1_General_CP1_CI_AS
3     SQLCHAR     0     4     ""      3     DRTT        SQL_Latin1_General_CP1_CI_AS
4     SQLCHAR     0     10     ""     4     DRKY        SQL_Latin1_General_CP1_CI_AS
5     SQLCHAR     0     1     ""      5     Empty2      SQL_Latin1_General_CP1_CI_AS  
6     SQLCHAR     0     30     ""     6     DRDL01      SQL_Latin1_General_CP1_CI_AS
7     SQLCHAR     0     1     ""      7     Empty3      SQL_Latin1_General_CP1_CI_AS
8     SQLCHAR     0     1024    "\n"  8     Remainder   SQL_Latin1_General_CP1_CI_AS

来自 Microsoft documentation,这是 .fmt 文件的文件格式: