通过 SQLXMLBULKLOADLib 插入时防止重复

Prevent duplicates when insert by SQLXMLBULKLOADLib

我想知道在我们使用 SQLXMLBULKLOADLib 时是否有办法防止插入重复行?我尝试将 UNIQUE NONCLUSTERED INDEX 添加到 SQL table,但是 SQLXMLBulkLoad4Class 插入失败。

所以我的代码看起来像这样

SQLXMLBULKLOADLib.SQLXMLBulkLoad4Class objBL = new SQLXMLBULKLOADLib.SQLXMLBulkLoad4Class();  
objBL.ConnectionString = "Provider=sqloledb;server=server;database=databaseName;integrated security=SSPI";  
objBL.ErrorLogFile = "error.xml";  
objBL.KeepIdentity = false;  
objBL.Execute ("schema.xml","data.xml");

我的 xml 看起来像这样:

<?xml version="1.0" encoding="UTF-8"?>
<foo>
   <row>
      <BICYCLE_NUM>624</BICYCLE_NUM>
      <BICYCLE_ORDER>1</BICYCLE_ORDER>      
   </row>
   <row>
      <BICYCLE_NUM>623</BICYCLE_NUM>
      <BICYCLE_ORDER>2</BICYCLE_ORDER>      
   </row>
   <row>
      <BICYCLE_NUM>681</BICYCLE_NUM>
      <BICYCLE_ORDER>3</BICYCLE_ORDER>      
   </row>
   <row>
      <BICYCLE_NUM>625</BICYCLE_NUM>
      <BICYCLE_ORDER>4</BICYCLE_ORDER>      
   </row>
   <row>
      <BICYCLE_NUM>680</BICYCLE_NUM>
      <BICYCLE_ORDER>5</BICYCLE_ORDER>      
   </row>
</foo>

而 XSD 看起来像这样:

<xsd:schema xmlns:xsd="http://www.w3.org/2001/XMLSchema"  
        xmlns:sql="urn:schemas-microsoft-com:mapping-schema">  
<xsd:element name="row" sql:relation="BICYCLE"   
                        sql:key-fields="BICYCLE_NUM">  
    <xsd:complexType> 
        <xsd:sequence>
            <xsd:element name="BICYCLE_NUM"   type="xsd:integer" />   
            <xsd:element name="BICYCLE_ORDER"   type="xsd:integer" />  
        </xsd:sequence>
    </xsd:complexType>
</xsd:element>

SQL table 看起来像这样:

CREATE TABLE BICYCLE (  
         BICYCLE_NUM   INT ,  
         BICYCLE_ORDER INT 
GO  

CREATE UNIQUE NONCLUSTERED INDEX IX_BICYCLE_NUM__BICYCLE_ORDER
   ON Wagon (BICYCLE_NUM, BICYCLE_ORDER);

我试过设置CheckConstraints = true,结果还是一样

SQLXMLBULKLOADLib.SQLXMLBulkLoad4Class objBL = new SQLXMLBULKLOADLib.SQLXMLBulkLoad4Class
            {
                ConnectionString = connectionString,
                ErrorLogFile = "error.xml",
                KeepIdentity = true,
                CheckConstraints = true
            };

我的问题是如何防止使用 SQLXMLBULKLOADLib 插入重复项?

探索 SQLXMLBulkLoad4Class 后,发现 IgnoreDuplicateKeys 属性。所以我们可以使用 IgnoreDuplicateKeys 属性:

SQLXMLBULKLOADLib.SQLXMLBulkLoad4Class objBL = new SQLXMLBULKLOADLib.SQLXMLBulkLoad4Class
{
    ConnectionString = connectionString,
    ErrorLogFile = "error.xml",
    ISQLXMLBulkLoad_IgnoreDuplicateKeys = true,
    IgnoreDuplicateKeys = true
};
objBL.Execute(xsdScheme, xmlFileName);

另外,应该用CONSTRAINT,而不是UNIQUE NONCLUSTERED INDEX

CREATE TABLE BICYCLE 
(  
      BICYCLE_NUM   INT
    , BICYCLE_ORDER INT
    , CONSTRAINT PK_BICYCLENUM_BICYCLEORDER PRIMARY KEY 
        NONCLUSTERED (BICYCLE_NUM, BICYCLE_ORDER)    
)
GO