如何将分号分隔的文本文件导入SQL Server

时间:2018-02-12 18:53:11

标签: sql sql-server xml import bcp

我正在尝试将分号分隔的文件导入SQL Server。我使用bcp尝试创建一个XML文件,但是我遇到了错误。

文本文件(数据)如下所示:

customer_id;remed_date;assumed_closed;exempt_ind;refresh_date;Target_date;due_date
2;06/06/2015;True;False;06/13/2015;06/13/2020;
3;08/02/2014;False;False;;08/02/2019;

XML文件如下:

<?xml version="1.0"?>
<BCPFORMAT xmlns="http://schemas.microsoft.com/sqlserver/2004/bulkload/format" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
 <RECORD>
  <FIELD ID="1" xsi:type="CharTerm" TERMINATOR=";" MAX_LENGTH="12"/>
  <FIELD ID="2" xsi:type="CharTerm" TERMINATOR=";" MAX_LENGTH="11"/>
  <FIELD ID="3" xsi:type="CharTerm" TERMINATOR=";" MAX_LENGTH="1"/>
  <FIELD ID="4" xsi:type="CharTerm" TERMINATOR=";" MAX_LENGTH="1"/>
  <FIELD ID="5" xsi:type="CharTerm" TERMINATOR=";" MAX_LENGTH="11"/>
  <FIELD ID="6" xsi:type="CharTerm" TERMINATOR=";" MAX_LENGTH="11"/>
  <FIELD ID="7" xsi:type="CharTerm" TERMINATOR="0x0A" MAX_LENGTH="11"/>
 </RECORD>
 <ROW>
  <COLUMN SOURCE="1" NAME="Customer_ID" xsi:type="SQLINT"/>
  <COLUMN SOURCE="2" NAME="Remed_Date" xsi:type="SQLNVARCHAR"/>
  <COLUMN SOURCE="3" NAME="Assumed_Closed" xsi:type="SQLBIT"/>
  <COLUMN SOURCE="4" NAME="Exempt_Ind" xsi:type="SQLBIT"/>
  <COLUMN SOURCE="5" NAME="Refresh_Date" xsi:type="SQLDATE"/>
  <COLUMN SOURCE="6" NAME="Target_Date" xsi:type="SQLDATE"/>
  <COLUMN SOURCE="7" NAME="Due_Date" xsi:type="SQLDATE"/>
 </ROW>
</BCPFORMAT>

表格如下:

[ODS_Customer_ID] [int] NOT NULL,
[Remed_Date] [date] NOT NULL,
[Assumed_Closed] [bit] NOT NULL,
[Exempt_Ind] [bit] NOT NULL,
[Refresh_Date] [date] NOT NULL,
[Target_Date] [date] 
[Due_Date] [date] 

当我尝试运行BULK INSERT时:

BULK INSERT MXB.dbo.RefreshSuppression
FROM '\\SRVR1\Data\MXB\Automated\BSA_AML_Suppression.txt'
(FORMATFILE = '\\SRVR1\Scripts\MXB\Weekly\MXBRefreshSupp.xml');

我收到此错误:

Msg 4864, Level 16, State 1, Line 26
Bulk load data conversion error (type mismatch or invalid character for the specified codepage) for row 1, column 1 (ODS_Customer_ID).
Msg 4866, Level 16, State 8, Line 26
The bulk load failed. The column is too long in the data file for row 1, column 7. Verify that the field terminator and row terminator are specified correctly.
Msg 7399, Level 16, State 1, Line 26
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 26
Cannot fetch a row from OLE DB provider "BULK" for linked server "(null)".

有什么想法吗?

2 个答案:

答案 0 :(得分:2)

对于消息4864,您无需将文件转换为XML即可执行批量插入。尝试:

BULK INSERT MXB.dbo.RefreshSuppression
FROM '\\SRVR1\Data\MXB\Automated\BSA_AML_Suppression.txt'
WITH (
    FIELDTERMINATOR = ';',
    ROWTERMINATOR = '\n'
    )
GO

可以找到有关批量导入的更多选项here.

对于消息4866,您缺少文件中的第7列。

消息7330&amp; 7399似乎与您的关联服务器有关,而不是您的批量上传。您可以找到适合他们的微软支持文章here.

答案 1 :(得分:1)

您的数据只有六列。在布尔值'Exempt_Ind'之后应该有三个日期,但我只计算两个。