Aracılığıyla paylaş


XML toplu yükleme örnekleri (SQLXML 4.0)

Aşağıdaki örnekler Microsoft XML toplu yükleme işlevselliğini göstermektedir. SQL Server. Bir XSD şeması ve bunun karşılığı XDR şeması, her bir örnek sağlar.

Toplu Yükleyici komut dosyası (ValidateAndBulkload.vbs)

Yazılan aşağıdaki komut dosyası kullanan kullanan dosyası kullanan, Microsoft Visual Basic komut dosyası kullanan Edition (VBScript), XML DOM içinde bir XML belgesi yükler; bu bir şemaya karşı doğrular ve, belgeyi geçerliyse, bir XML toplu yükleme için yük uygulamasına XML yürütür bir SQL Server TABLO. Bu komut, bu konuda daha sonra başvurmak için bağımsız örneklerin her kullanılabilir.

Not

Içerik veri dosyasından karşıya, XML toplu yükleme bir uyarı veya hata durum değil.Bu nedenle, XML veri dosyası için bir toplu yükleme işlemi çalıştırmadan önce doğrulamak için yararlı olur.

Dim FileValid

set objBL = CreateObject("SQLXMLBulkLoad.SQLXMLBulkload.4.0")
objBL.ConnectionString = "provider=SQLOLEDB;data source=MyServer;database=tempdb;integrated security=SSPI"
objBL.ErrorLogFile = "c:\error.log"

'Validate the data file prior to bulkload
Dim sOutput 
sOutput = ValidateFile("SampleXMLData.xml", "", "SampleSchema.xml")
WScript.Echo sOutput

If FileValid Then
   ' Check constraints and initiate transaction (if needed)
   ' objBL.CheckConstraints = True
   ' objBL.Transaction=True
  'Execute XML bulkload using file.
  objBL.Execute "SampleSchema.xml", "SampleXMLData.xml"
  set objBL=Nothing
End If

Function ValidateFile(strXmlFile,strUrn,strXsdFile)
    
   ' Create a schema cache and add SampleSchema.xml to it.
   Dim xs, fso, sAppPath
   Set fso = CreateObject("Scripting.FileSystemObject") 
   Set xs = CreateObject("MSXML2.XMLSchemaCache.6.0")
   sAppPath = fso.GetFolder(".") 
   xs.Add strUrn, sAppPath & "\" & strXsdFile

   ' Create an XML DOMDocument object.
   Dim xd 
   Set xd = CreateObject("MSXML2.DOMDocument.6.0")

   ' Assign the schema cache to the DOM document.
   ' schemas collection.
   Set xd.schemas = xs

   ' Load XML document as DOM document.
   xd.async = False
   xd.Load sAppPath & "\" & strXmlFile

   ' Return validation results in message to the user.
   If xd.parseError.errorCode <> 0 Then
        ValidateFile = "Validation failed on " & _
             strXmlFile & vbCrLf & _
             "=====================" & vbCrLf & _
             "Reason: " & xd.parseError.reason & _
             vbCrLf & "Source: " & _
             xd.parseError.srcText & _
             vbCrLf & "Line: " & _
             xd.parseError.Line & vbCrLf
             FileValid = False
    Else
        ValidateFile = "Validation succeeded for " & _
             strXmlFile & vbCrLf & _
             "======================" & _
             vbCrLf & "Contents to be bulkloaded" & vbCrLf
             FileValid = True
    End If
End Function

C.Toplu bir tabloda XML yükleme

Bu örnek bir bağlantı örneğini oluşturur... SQL Server ' de belirtilen ConnectionString özellik (sunucum). Örnekte ayrıca belirtir ErrorLogFile Özellik. Bu nedenle, farklı bir konuma değiştirmek için de karar verebilirsiniz, belirtilen dosyada ("C:\error.log"), hata çıktı kaydedilir.Ayrıca, fark Execute Yöntem parametrelerinin eşleme şema dosyasının (SampleSchema.xml) hem de XML veri dosyasını (SampleXMLData.xml) var. Ne zaman toplu yükleme, Müşt yürütür tablo oluşturmuş olabilirsiniz tempdb veritabanı, XML veri dosyasının içeriğini alarak yeni kayıtları içerecektir.

Bir örnek toplu yükleme sınamak için

  1. Bu tablo oluşturun:

    CREATE TABLE Cust(CustomerID  int PRIMARY KEY,
                      CompanyName varchar(20),
                      City        varchar(20))
    GO
    
  2. Tercih edilen metin veya XML Düzenleyicisi bir dosya oluşturun ve SampleSchema.xml kaydedin.Bu dosya için aşağıdaki XSD şeması ekleyin:

    <xsd:schema xmlns:xsd="http://www.w3.org/2001/XMLSchema"
                xmlns:sql="urn:schemas-microsoft-com:mapping-schema">
       <xsd:element name="ROOT" sql:is-constant="1" >
         <xsd:complexType>
           <xsd:sequence>
             <xsd:element name="Customers" sql:relation="Cust" maxOccurs="unbounded">
               <xsd:complexType>
                 <xsd:sequence>
                   <xsd:element name="CustomerID"  type="xsd:integer" />
                   <xsd:element name="CompanyName" type="xsd:string" />
                   <xsd:element name="City"        type="xsd:string" />
                 </xsd:sequence>
               </xsd:complexType>
             </xsd:element>
           </xsd:sequence>
          </xsd:complexType>
         </xsd:element>
    </xsd:schema>
    
  3. Tercih edilen metin veya XML Düzenleyicisi bir dosya oluşturun ve SampleXMLData.xml kaydedin.Bu dosya için aşağıdaki XML belgesine ekleyin:

    <ROOT>
      <Customers>
        <CustomerID>1111</CustomerID>
        <CompanyName>Sean Chai</CompanyName>
        <City>New York</City>
      </Customers>
      <Customers>
        <CustomerID>1112</CustomerID>
        <CompanyName>Tom Johnston</CompanyName>
         <City>Los Angeles</City>
      </Customers>
      <Customers>
        <CustomerID>1113</CustomerID>
        <CompanyName>Institute of Art</CompanyName>
        <City>Chicago</City>
      </Customers>
    </ROOT>
    
  4. Tercih edilen metin veya XML Düzenleyicisi bir dosya oluşturun ve ValidateAndBulkload.vbs kaydedin.Bu dosyayı, yukarıda sağlanan VBScript kodu, bu konunun başında ekleyin.Bağlantı değiştir dize uygun sunucu adı sağlamak için.Parametre için belirtilen dosyalar için uygun yol belirtin Execute yöntem.

  5. yürütmek VBScript kodu.XML toplu yükleme özel XML yükler tablo.

Bu, eşdeğer XDR şeması oluşur:

<?xml version="1.0" ?>
<Schema xmlns="urn:schemas-microsoft-com:xml-data" 
        xmlns:dt="urn:schemas-microsoft-com:xml:datatypes"  
        xmlns:sql="urn:schemas-microsoft-com:xml-sql" > 

   <ElementType name="CustomerID" dt:type="int" />
   <ElementType name="CompanyName" dt:type="string" />
   <ElementType name="City" dt:type="string" />

   <ElementType name="ROOT" sql:is-constant="1">
      <element type="Customers" />
   </ElementType>

   <ElementType name="Customers"  sql:relation="Cust" >
      <element type="CustomerID"  sql:field="CustomerID" />
      <element type="CompanyName" sql:field="CompanyName" />
      <element type="City"        sql:field="City" />

   </ElementType>
</Schema>

b.Toplu XML verileri birden çok tablo yükleme

Bu örnekte, XML belgesinin oluşur <Müşteri> ve <Sipariş> öğeleri.

<ROOT>
  <Customers>
    <CustomerID>1111</CustomerID>
    <CompanyName>Sean Chai</CompanyName>
    <City>NY</City>
    <Order OrderID="1" />
    <Order OrderID="2" />
  </Customers>
  <Customers>
    <CustomerID>1112</CustomerID>
    <CompanyName>Tom Johnston</CompanyName>
     <City>LA</City>  
    <Order OrderID="3" />
  </Customers>
  <Customers>
    <CustomerID>1113</CustomerID>
    <CompanyName>Institute of Art</CompanyName>
    <Order OrderID="4" />
  </Customers>
</ROOT>

Bu örnekte toplu iki tabloya, XML verilerini yükler. Müşteri and CustOrder:

Cust(CustomerID, CompanyName, City)
CustOrder(OrderID, CustomerID)

Aşağıdaki XSD şeması, XML görünümü tabloları tanımlar.Üst-altöge ilişkisi şema belirtir <Müşteri> ve <Sipariş> öğeleri.

<xsd:schema xmlns:xsd="http://www.w3.org/2001/XMLSchema"
            xmlns:sql="urn:schemas-microsoft-com:mapping-schema">
  <xsd:annotation>
    <xsd:appinfo>
      <sql:relationship name="CustCustOrder"
          parent="Cust"
          parent-key="CustomerID"
          child="CustOrder"
          child-key="CustomerID" />
    </xsd:appinfo>
  </xsd:annotation>
  <xsd:element name="ROOT" sql:is-constant="1" >
    <xsd:complexType>
      <xsd:sequence>
        <xsd:element name="Customers" sql:relation="Cust" >
          <xsd:complexType>
            <xsd:sequence>
              <xsd:element name="CustomerID"  type="xsd:integer" />
              <xsd:element name="CompanyName" type="xsd:string" />
              <xsd:element name="City"        type="xsd:string" />
              <xsd:element name="Order" 
                          sql:relation="CustOrder"
                          sql:relationship="CustCustOrder" >
                <xsd:complexType>
                  <xsd:attribute name="OrderID" type="xsd:integer" />
                </xsd:complexType>
              </xsd:element>
             </xsd:sequence>
          </xsd:complexType>
        </xsd:element>
      </xsd:sequence>
    </xsd:complexType>
  </xsd:element>
</xsd:schema>

Birincil anahtara yabancı anahtar ilişkisi arasındaki, yukarıda belirtilen XML toplu yükleme kullanan <Müşteri> ve <CustOrder> öğeleri için toplu verilerin her iki tabloya yüklenemedi.

Bir örnek toplu yükleme sınamak için

  1. Iki tablo oluşturun. tempdb veritabanı:

    USE tempdb
    CREATE TABLE Cust(
           CustomerID  int PRIMARY KEY,
           CompanyName varchar(20),
           City        varchar(20))
    CREATE TABLE CustOrder(        OrderID     int PRIMARY KEY, 
            CustomerID int FOREIGN KEY REFERENCES Cust(CustomerID))
    
  2. Tercih edilen metin veya XML Düzenleyicisi bir dosya oluşturun ve SampleSchema.xml kaydedin.Bu örnekte, dosya için sağlanan XSD şeması ekleyin.

  3. Tercih edilen metin veya XML Düzenleyicisi bir dosya oluşturun ve SampleData.xml kaydedin.Bu örnek dosya için daha önce verilen XML belgesi ekleyin.

  4. Tercih edilen metin veya XML Düzenleyicisi bir dosya oluşturun ve ValidateAndBulkload.vbs kaydedin.Bu dosyayı, yukarıda sağlanan VBScript kodu, bu konunun başında ekleyin.Uygun sunucu ve veritabanı adı sağlamak için bağlantı dizesi değiştirin.Parametre için belirtilen dosyalar için uygun yol belirtin Execute yöntem.

  5. VBScript kodu, yukarıdaki yürütün.XML toplu yükleme XML belgesini özel ve CustOrder tablolarına yükler.

Bu, eşdeğer XDR şeması oluşur:

<?xml version="1.0" ?>
<Schema xmlns="urn:schemas-microsoft-com:xml-data" 
        xmlns:dt="urn:schemas-microsoft-com:xml:datatypes"  
        xmlns:sql="urn:schemas-microsoft-com:xml-sql" > 
   <ElementType name="CustomerID" dt:type="int" />
   <ElementType name="CompanyName" dt:type="string" />
   <ElementType name="City" dt:type="string" />

   <ElementType name="ROOT" sql:is-constant="1">
      <element type="Customers" />
   </ElementType>

   <ElementType name="Customers" sql:relation="Cust" >
      <element type="CustomerID" sql:field="CustomerID" />
      <element type="CompanyName" sql:field="CompanyName" />
      <element type="City" sql:field="City" />
      <element type="Order" >
<sql:relationship
                key-relation="Cust"
                key="CustomerID"
                foreign-key="CustomerID"
                foreign-relation="CustOrder" />
      </element>
   </ElementType>
    <ElementType name="Order" sql:relation="CustOrder" >
      <AttributeType name="OrderID" />
      <AttributeType name="CustomerID" />
      <attribute type="OrderID" />
      <attribute type="CustomerID" />
    </ElementType>
</Schema>

c.Toplu yükleme XML şemaya zinciri ilişkileri kullanma

Bu örnek, nasıl eşleme şemada belirtilen M:N ilişki XML Bulk yükü tarafından veri yüklemek için kullanılan gösterir bir tablo, bir M:N ilişkiyi temsil eder.

Örneğin, bu XSD şeması göz önünde bulundurun:

<xsd:schema xmlns:xsd="http://www.w3.org/2001/XMLSchema"
            xmlns:sql="urn:schemas-microsoft-com:mapping-schema">
<xsd:annotation>
  <xsd:appinfo>
    <sql:relationship name="OrderOD"
          parent="Ord"
          parent-key="OrderID"
          child="OrderDetail"
          child-key="OrderID" />

    <sql:relationship name="ODProduct"
          parent="OrderDetail"
          parent-key="ProductID"
          child="Product"
          child-key="ProductID" 
          inverse="true"/>
  </xsd:appinfo>
</xsd:annotation>

  <xsd:element name="ROOT" sql:is-constant="1" >
    <xsd:complexType>
      <xsd:sequence>
        <xsd:element name="Order" 
                     sql:relation="Ord" 
                     sql:key-fields="OrderID" >
          <xsd:complexType>
            <xsd:sequence>
             <xsd:element name="Product"
                          sql:relation="Product" 
                          sql:key-fields="ProductID"
                          sql:relationship="OrderOD ODProduct">
               <xsd:complexType>
                 <xsd:attribute name="ProductID" type="xsd:int" />
                 <xsd:attribute name="ProductName" type="xsd:string" />
               </xsd:complexType>
             </xsd:element>
           </xsd:sequence>
           <xsd:attribute name="OrderID"   type="xsd:integer" /> 
           <xsd:attribute name="CustomerID"   type="xsd:string" />
         </xsd:complexType>
       </xsd:element>
      </xsd:sequence>
    </xsd:complexType>
  </xsd:element>
</xsd:schema>

Şema belirtir bir <Sipariş> öğeyle bir <Ürün> alt öğe. The <Order> element maps to Ord tablo and the <Product> element maps to the Product tablo in the database. Belirtilen zinciri ilişki <Ürün> öğe tarafından OrderDetail temsil M:N ilişki tanımlar tablo. (Siparişte birçok ürün ekleyebilirsiniz ve bir ürün birçok siparişlerindeki eklenebilir.)

Kayıtlar, toplu bu şemayı bir XML belgesiyle yükleme olduğunda, sipariş, ürün ve OrderDetail tablolara eklenir.

Bir çalışan örneği sınamak için

  1. Üç tablo oluşturun:

    CREATE TABLE Ord (
             OrderID     int  PRIMARY KEY,
             CustomerID  varchar(5))
    GO
    CREATE TABLE Product (
             ProductID   int PRIMARY KEY,
             ProductName varchar(20))
    GO
    CREATE TABLE OrderDetail (
           OrderID     int FOREIGN KEY REFERENCES Ord(OrderID),
           ProductID   int FOREIGN KEY REFERENCES Product(ProductID),
                       CONSTRAINT OD_key PRIMARY KEY (OrderID, ProductID))
    GO
    
  2. Bu örnekte, yukarıda sağlanan şema SampleSchema.xml kaydedin.

  3. Aşağıdaki örnek XML verileri SampleXMLData.xml kaydedin:

    <ROOT>  
      <Order OrderID="1" CustomerID="ALFKI">
        <Product ProductID="1" ProductName="Chai" />
        <Product ProductID="2" ProductName="Chang" />
      </Order>
      <Order OrderID="2" CustomerID="ANATR">
        <Product ProductID="3" ProductName="Aniseed Syrup" />
        <Product ProductID="4" ProductName="Gumbo Mix" />
      </Order>
    </ROOT>
    
  4. Tercih edilen metin veya XML Düzenleyicisi bir dosya oluşturun ve ValidateAndBulkload.vbs kaydedin.Bu dosyayı, yukarıda sağlanan VBScript kodu, bu konunun başında ekleyin.Uygun sunucu ve veritabanı adı sağlamak için bağlantı dizesi değiştirin.Bu örnek için kaynak kodundan aşağıdaki satırları uncomment.

    objBL.CheckConstraints = True
    objBL.Transaction=True
    
  5. yürütmek VBScript kodu.XML toplu yükleme XML belgesinde, sipariş ve ürün tablolarına yükler.

d.Toplu kimlik türü sütunlarda yükleme

Bu örnek, toplu yükleme kimliği türü sütunlarındaki işleme biçimini gösterir.Bu örnekte, üç tabloya (sipariş, ürün ve OrderDetail) yüklenen bir yığın veridir.

Bu tablolar:

  • Sipariş, sipariş kimliği tablo türü kimlik sütun olan

  • Productıd Ürün tablosundaki bir kimlik türü sütundur.

  • OrderDetail sipariş kimliği ve ürün kimliği sütunlar, yabancı anahtar sütunları sipariş ve ürün tablolardaki ilgili birincil anahtar sütunlarını başvuruda ' dir.

Bu örnek tablo şemalar şunlardır:

Ord (OrderID, CustomerID)
Product (ProductID, ProductName)
OrderDetail (OrderID, ProductID)

Bu örnekte, XML toplu yükleme, KeepIdentity özellik BulkLoad nesne modeli, false olarak küme. Bu nedenle, SQL Server Ürün ve sipariş tablolarında, sırasıyla Productıd ve SiparişNo sütunların kimlik değerlerini oluşturur (belgelerde yüklenen bir yığın olarak sağlanan herhangi bir değeri göz ardı edilir).

Bu durum, tablolar arasında birincil anahtara yabancı anahtar ilişkisi XML toplu yükleme tanımlar.Toplu yükleme önce kayıtları tablolarda birincil anahtar ile ekler, sonra tarafından oluşturulan Kimlik değerini yayar. SQL Server yabancı anahtar sütunları olan tablolar için. Aşağıdaki örnekte, bu sırada tablolardaki verileri XML toplu yükleme ekler:

  1. Ürün

  2. Sipariş

  3. OrderDetail

    Not

    Ürünler ve Orders tablo s oluşturulan kimlik değerlerini yaymak için bu değerleri daha sonra ekleme OrderDetails içine izlemek XML toplu yükleme işleme mantığına gerektirir tablo.Bunu yapmak için , XML toplu yükleme ara tablolar oluşturur, bu tablolardaki verileri doldurur ve daha sonra bunları kaldırır.

Bir çalışan örneği sınamak için

  1. Bu tablo oluşturun:

    CREATE TABLE Ord (
             OrderID     int identity(1,1)  PRIMARY KEY,
             CustomerID  varchar(5))
    GO
    CREATE TABLE Product (
             ProductID   int identity(1,1) PRIMARY KEY,
             ProductName varchar(20))
    GO
    CREATE TABLE OrderDetail (
           OrderID     int FOREIGN KEY REFERENCES Ord(OrderID),
           ProductID   int FOREIGN KEY REFERENCES Product(ProductID),
                       CONSTRAINT OD_key PRIMARY KEY (OrderID, ProductID))
    GO
    
  2. Tercih edilen metin veya XML Düzenleyicisi bir dosya oluşturun ve SampleSchema.xml kaydedin.Bu bir XSD şeması, bu dosyaya ekleyin.

    <xsd:schema xmlns:xsd="http://www.w3.org/2001/XMLSchema"
                xmlns:sql="urn:schemas-microsoft-com:mapping-schema">
     <xsd:annotation>
       <xsd:appinfo>
        <sql:relationship name="OrderOD"
              parent="Ord"
              parent-key="OrderID"
              child="OrderDetail"
              child-key="OrderID" />
        <sql:relationship name="ODProduct"
              parent="OrderDetail"
              parent-key="ProductID"
              child="Product"
              child-key="ProductID" 
              inverse="true"/>
       </xsd:appinfo>
     </xsd:annotation>
    
      <xsd:element name="Order" sql:relation="Ord" 
                                sql:key-fields="OrderID" >
       <xsd:complexType>
         <xsd:sequence>
            <xsd:element name="Product" sql:relation="Product" 
                         sql:key-fields="ProductID"
                         sql:relationship="OrderOD ODProduct">
              <xsd:complexType>
                 <xsd:attribute name="ProductID" type="xsd:int" />
                 <xsd:attribute name="ProductName" type="xsd:string" />
              </xsd:complexType>
            </xsd:element>
         </xsd:sequence>
            <xsd:attribute name="OrderID"   type="xsd:integer" /> 
            <xsd:attribute name="CustomerID"   type="xsd:string" />
        </xsd:complexType>
      </xsd:element>
    </xsd:schema>
    
  3. Tercih edilen metin veya XML Düzenleyicisi bir dosya oluşturun ve SampleXMLData.xml kaydedin.Aşağıdaki XML belgesine ekleyin.

    <ROOT>  
      <Order OrderID="11" CustomerID="ALFKI">
        <Product ProductID="11" ProductName="Chai" />
        <Product ProductID="22" ProductName="Chang" />
      </Order>
      <Order OrderID="22" CustomerID="ANATR">
         <Product ProductID="33" ProductName="Aniseed Syrup" />
        <Product ProductID="44" ProductName="Gumbo Mix" />
      </Order>
    </ROOT>
    
  4. Tercih edilen metin veya XML Düzenleyicisi bir dosya oluşturun ve ValidateAndBulkload.vbs kaydedin.Bu dosya için aşağıdaki VBScript kodu ekleyin.Uygun sunucu ve veritabanı adı sağlamak için bağlantı dizesi değiştirin.Uygun yol için parametre olarak hizmet veren dosyaları için belirttiğiniz yürütmek yöntem.

    Set objBL = CreateObject("SQLXMLBulkLoad.SQLXMLBulkload.4.0")
    objBL.ConnectionString = "provider=SQLOLEDB;data source=localhost;database=tempdb;integrated security=SSPI"
    objBL.ErrorLogFile = "C:\error.log"
    objBL.CheckConstraints = True
    objBL.Transaction = False
    objBL.KeepIdentity = False
    objBL.Execute "SampleSchema.xml", "SampleXMLData.xml"
    Set objBL = Nothing
    MsgBox "Done."
    
  5. yürütmek VBScript kodu.XML toplu yükleme verileri ilgili tablolara yükleyecektir.

e.Toplu yükleme önce tablo şemaları oluşturma

Önce toplu yükleme yoksa, XML Bulk Load isteğe bağlı tabloları oluşturabilirsiniz.Ayarlama SchemaGen özellik SQLXMLBulkLoad Nesne TRUE olarak yapar. Ayrıca isteğe bağlı olarak, varolan herhangi bir tablo bırakma ayarlayarak bunları yeniden oluşturmak için XML toplu yükleme isteyebilirler SGDropTables özellik TRUE olarak. Aşağıdaki örnek VBScript bu özelliklerin kullanılışını gösterir.

Ayrıca, bu örnek iki ek özelliği TRUE olarak ayarlar:

  • CheckConstraints.Setting this property to TRUE ensures that the data being inserted into the tables does not violate any constraints that have been specified on the tables (in this case the PRIMARY KEY/FOREIGN KEY constraints specified between the Cust and CustOrder tables).Bir kısıtlama ihlali ise, toplu yükleme başarısız olur.

  • XMLFragment.This property must be set to TRUE because the sample XML document (data source) contains no single, top-level element (and is thus a fragment).

VBScript kodu budur:

Dim objBL 
Set objBL = CreateObject("SQLXMLBulkLoad.SQLXMLBulkload.4.0")
objBL.ConnectionString = "provider=SQLOLEDB;data source=localhost;database=tempdb;integrated security=SSPI"
objBL.ErrorLogFile = "c:\error.log"

objBL.CheckConstraints=true
objBL.XMLFragment = True
objBL.SchemaGen = True
objBL.SGDropTables = True

objBL.Execute "SampleSchema.xml", "SampleXMLData.xml"
Set objBL = Nothing

Bir çalışan örneği sınamak için

  1. Tercih edilen metin veya XML Düzenleyicisi bir dosya oluşturun ve SampleSchema.xml kaydedin.Sağlanan XSD şeması, önceki örnekte, "Kullanma zinciri ilişkileri için toplu yükleme XML şemasındaki" dosyaya ekleyin.

  2. Tercih edilen metin veya XML Düzenleyicisi bir dosya oluşturun ve SampleXMLData.xml kaydedin.Sağlanan XML belgesini, önceki örnekte, "Kullanma zinciri ilişkileri için toplu yükleme XML şemasındaki" dosyaya ekleyin.Kaldırma <KÖK> öğe belgede (bir parça yapmak için ).

  3. Tercih edilen metin veya XML Düzenleyicisi bir dosya oluşturun ve ValidateAndBulkload.vbs kaydedin.Bu dosya için bu örnekte VBScript kodunu ekleyin.Uygun sunucu ve veritabanı adı sağlamak için bağlantı dizesi değiştirin.Parametre için belirtilen dosyalar için uygun yol belirtin Execute yöntem.

  4. yürütmek VBScript kodu.XML toplu yükleme sağlanan ve toplu yükü olan eşleme şema temel alınarak gerekli tabloları verileri de oluşturur.

f.Toplu bir yükleme

The Execute yöntem of the XML toplu yükleme object model takes two parameters. Şema eşleme dosyası ilk parametredir.Ikinci parametre veritabanına yüklenebilmesi için XML verileri sağlar.XML verilerini geçirmek için iki yol vardır Execute XML toplu yükleme yöntem:

  • Dosya adı parametresi olarak belirtin.

  • XML verilerini içeren bir akış geçirir.

Bu örnek, gelen bir akış yükü toplu olarak verilmektedir.

VBScript, önce Northwind veritabanını Müşteriler tablosunda müşteri bilgilerini almak için bir deyim yürütür.SELECT deyiminde (ÖĞELER seçeneği ile) FOR XML yan tümce belirtildiğinden, sorguyu bu formun öğe merkezli bir XML belgesi döndürür:

<Customer>
  <CustomerID>..</CustomerID>
  <CompanyName>..</CompanyName>
  <City>..</City>
</Customer>
...

Komut dosyası, XML akışı için olarak sonra geçirmeden Execute yöntem, ikinci parametre olarak. The Execute yöntem bulk loads the data into the Cust tablo.

Bu komut dosyası ayarlar için SchemaGen özellik TRUE olarak ve SGDropTables özellik TRUE olarak, XML toplu yükleme, belirtilen veritabanına özel tablo oluşturur. (Tablo önceden varsa, ilk tablonun düşünceye ve sonra yeniden oluşturur.)

Bu, VBScript örneği şöyledir:

Set objBL = CreateObject("SQLXMLBulkLoad.SQLXMLBulkload.4.0")
Set objCmd = CreateObject("ADODB.Command")
Set objConn = CreateObject("ADODB.Connection")
Set objStrmOut = CreateObject ("ADODB.Stream")

objBL.ConnectionString = "provider=SQLOLEDB;data source=localhost;database=tempdb;integrated security=SSPI"
objBL.ErrorLogFile     = "c:\error.log"
objBL.CheckConstraints = True
objBL.SchemaGen        = True
objBL.SGDropTables     = True
objBL.XMLFragment      = True
' Open a connection to the instance of SQL Server to get the source data.

objConn.Open "provider=SQLOLEDB;server=(local);database=tempdb;integrated security=SSPI"
Set objCmd.ActiveConnection = objConn
objCmd.CommandText = "SELECT CustomerID, CompanyName, City FROM Customers FOR XML AUTO, ELEMENTS"

' Open the return stream and execute the command.
Const adCRLF = -1
Const adExecuteStream = 1024
objStrmOut.Open
objStrmOut.LineSeparator = adCRLF
objCmd.Properties("Output Stream").Value = objStrmOut
objCmd.Execute , , adExecuteStream
objStrmOut.Position = 0

' Execute bulk load. Read source XML data from the stream.
objBL.Execute "SampleSchema.xml", objStrmOut

Set objBL = Nothing

Aşağıdaki XSD eşleme şemasına tablo oluşturmak için gerekli bilgileri sağlar:

<xsd:schema xmlns:xsd="http://www.w3.org/2001/XMLSchema"
            xmlns:sql="urn:schemas-microsoft-com:mapping-schema">
<xsd:element name="ROOT" sql:is-constant="true" >
  <xsd:complexType>
    <xsd:sequence>
      <xsd:element ref="Customers"/>
    </xsd:sequence>
  </xsd:complexType>
</xsd:element>
<xsd:element name="Customers" sql:relation="Cust" >
  <xsd:complexType>
    <xsd:sequence>
      <xsd:element name="CustomerID"
                   type="xsd:string"
                   sql:datatype="nvarchar(5)"/>
      <xsd:element name="CompanyName"
                   type="xsd:string"
                   sql:datatype="nvarchar(40)"/>
      <xsd:element name="City"
                   type="xsd:string"
                   sql:datatype="nvarchar(40)"/>
    </xsd:sequence>
  </xsd:complexType>
</xsd:element>
</xsd:schema>

Bu, eşdeğer XDR şeması oluşur:

<?xml version="1.0" ?>
<Schema xmlns="urn:schemas-microsoft-com:xml-data" 
        xmlns:dt="urn:schemas-microsoft-com:xml:datatypes"  
        xmlns:sql="urn:schemas-microsoft-com:xml-sql" >
   <ElementType name="CustomerID" dt:type="int" />
   <ElementType name="CompanyName" dt:type="string" />
   <ElementType name="City" dt:type="string" />

   <ElementType name="root" sql:is-constant="1">
      <element type="Customers" />
   </ElementType>

   <ElementType name="Customers" sql:relation="Cust"  >
      <element type="CustomerID" sql:field="CustomerID" />
      <element type="CompanyName" sql:field="CompanyName" />
      <element type="City" sql:field="City" />
    </ElementType>
</Schema>

Varolan bir dosya üzerinde bir akış açma

Ayrıca bir akışta varolan bir XML veri dosyasını açın ve akışı, parametre olarak geçirmek Execute yöntem (yerine, dosya adı, parametre olarak geçirerek).

Bu parametre olarak bir akış geçirerek, bir Visual Basic örnektir:

Private Sub Form_Load()
Dim objBL As New SQLXMLBulkLoad
Dim objStrm As New ADODB.Stream
Dim objFileSystem As New Scripting.FileSystemObject
Dim objFile As Scripting.TextStream

MsgBox "Begin BulkLoad..."
objBL.ConnectionString = "provider=SQLOLEDB;data source=localhost;database=tempdb;integrated security=SSPI"
objBL.ErrorLogFile = "c:\error.log"
objBL.CheckConstraints = True
objBL.SchemaGen = True
objBL.SGDropTables = True
' Here again a stream is specified that contains the source data 
' (instead of the file name). But this is just an illustration.
' Usually this is useful if you have an XML data 
' stream that is created by some other means that you want to bulk 
' load. This example starts with an XML text file, so it may not be the 
' best to use a stream (you can specify the file name directly).
' Here you could have specified the file name itself. 
Set objFile = objFileSystem.OpenTextFile("c:\SampleData.xml")
objStrm.Open
objStrm.WriteText objFile.ReadAll
objStrm.Position = 0
objBL.Execute "c:\SampleSchema.xml", objStrm

Set objBL = Nothing
MsgBox "Done."
End Sub

Uygulama sınamak için , bir dosya (SampleData.xml) ve bu örnekte sağlanan XSD şeması aşağıdaki XML belgesinde kullanın:

XML kaynak verileri (SampleData.xml) budur:

<ROOT>
  <Customers>
    <CustomerID>1111</CustomerID>
    <CompanyName>Hanari Carnes</CompanyName>
    <City>NY</City>
    <Order OrderID="1" />
    <Order OrderID="2" />
  </Customers>

  <Customers>
    <CustomerID>1112</CustomerID>
    <CompanyName>Toms Spezialitten</CompanyName>
     <City>LA</City>
    <Order OrderID="3" />
  </Customers>
  <Customers>
    <CustomerID>1113</CustomerID>
    <CompanyName>Victuailles en stock</CompanyName>
    <Order CustomerID= "4444" OrderID="4" />
</Customers>
</ROOT>

Bu, eşdeğer XDR şeması oluşur:

<?xml version="1.0" ?>
<Schema xmlns="urn:schemas-microsoft-com:xml-data" 
        xmlns:dt="urn:schemas-microsoft-com:xml:datatypes"  
        xmlns:sql="urn:schemas-microsoft-com:xml-sql" >

    <ElementType name="Order" sql:relation="CustOrder" >
      <AttributeType name="OrderID" />
      <AttributeType name="CustomerID" />
      <attribute type="OrderID" />
      <attribute type="CustomerID" />
    </ElementType>

   <ElementType name="CustomerID" dt:type="int" />
   <ElementType name="CompanyName" dt:type="string" />
   <ElementType name="City" dt:type="string" />

   <ElementType name="root" sql:is-constant="1">
      <element type="Customers" />
   </ElementType>

   <ElementType name="Customers" sql:relation="Cust"  >
      <element type="CustomerID" sql:field="CustomerID" />
      <element type="CompanyName" sql:field="CompanyName" />
      <element type="City" sql:field="City" />
      <element type="Order" >
             <sql:relationship
                key-relation="Cust"
                key="CustomerID"
                foreign-key="CustomerID"
                foreign-relation="CustOrder" />
      </element>
   </ElementType>
</Schema>

g.Yığın Taşması sütunlarda yükleniyor

Eşleme şemada taşma belirtiyorsa sütun kullanarak sql:overflow-field Ek açıklamayı XML toplu yükleme tüm unconsumed veri kaynak belgeden bu kopyalar sütun.

Bu bir XSD şeması göz önünde bulundurun:

<xsd:schema xmlns:xsd="http://www.w3.org/2001/XMLSchema"
            xmlns:sql="urn:schemas-microsoft-com:mapping-schema">
<xsd:annotation>
  <xsd:appinfo>
    <sql:relationship name="CustCustOrder"
          parent="Cust"
          parent-key="CustomerID"
          child="CustOrder"
          child-key="CustomerID" />
  </xsd:appinfo>
</xsd:annotation>
  <xsd:element name="Customers" sql:relation="Cust"
                                sql:overflow-field="OverflowColumn" >
   <xsd:complexType>
     <xsd:sequence>
       <xsd:element name="CustomerID"  type="xsd:integer" />
       <xsd:element name="CompanyName" type="xsd:string" />
       <xsd:element name="City"        type="xsd:string" />
       <xsd:element name="Order" 
                          sql:relation="CustOrder"
                          sql:relationship="CustCustOrder" >
         <xsd:complexType>
          <xsd:attribute name="OrderID" type="xsd:integer" />
          <xsd:attribute name="CustomerID" type="xsd:integer" />
         </xsd:complexType>
       </xsd:element>
     </xsd:sequence>
    </xsd:complexType>
  </xsd:element>
</xsd:schema>

Şema taşma tanımlayan sütun (taşması sütun) Müşteri tablosu için.Sonuç olarak, tüm XML verilerini her biri için unconsumed <Müşteri> öğe için eklenen sütun.

Not

Tüm öğeler soyut (olan öğeler soyut = "true" belirtilir) ve tüm öznitelikleri engellendi (hangi öznitelikleriyasaklanmış = "true" belirtilen) taşma XML toplu yükleme düşünülür ve taşma sütun, belirtildiği takdirde eklenir.(Aksi halde, bunlar dikkate alınmaz.)

Bir çalışan örneği sınamak için

  1. Iki tablo oluşturun. tempdb veritabanı:

    USE tempdb
    CREATE TABLE Cust (
                  CustomerID     int         PRIMARY KEY,
                  CompanyName    varchar(20) NOT NULL,
                  City           varchar(20) DEFAULT 'Seattle',
                  OverflowColumn nvarchar(200))
    GO
    CREATE TABLE CustOrder (
                  OrderID    int PRIMARY KEY,
                  CustomerID int FOREIGN KEY 
                                 REFERENCES Cust(CustomerID))
    GO
    
  2. Tercih edilen metin veya XML Düzenleyicisi bir dosya oluşturun ve SampleSchema.xml kaydedin.Bu örnekte, dosya için sağlanan XSD şeması ekleyin.

  3. Tercih edilen metin veya XML Düzenleyicisi bir dosya oluşturun ve SampleXMLData.xml kaydedin.Aşağıdaki XML belgesi için dosyaya ekleyin:

    <ROOT>
      <Customers>
        <CustomerID>1111</CustomerID>
        <CompanyName>Hanari Carnes</CompanyName>
        <City><![CDATA[NY]]> </City>
        <Junk>garbage in overflow</Junk>
        <Order OrderID="1" />
        <Order OrderID="2" />
      </Customers>
    
      <Customers>
        <CustomerID>1112</CustomerID>
        <CompanyName>Toms Spezialitten</CompanyName>
         <![CDATA[LA]]> 
        <!-- <xyz><address>111 Maple, Seattle</address></xyz>   -->
        <Order OrderID="3" />
      </Customers>
      <Customers>
        <CustomerID>1113</CustomerID>
        <CompanyName>Victuailles en stock</CompanyName>
        <Order OrderID="4" />
    </Customers>
    </ROOT>
    
  4. Tercih edilen metin veya XML Düzenleyicisi bir dosya oluşturun ve ValidateAndBulkload.vbs kaydedin.Bu dosya için aşağıdaki Microsoft Visual Basic komut dosyası kullanan Edition (VBScript) kodu ekleyin.Uygun sunucu ve veritabanı adı sağlamak için bağlantı dizesi değiştirin.Parametre için belirtilen dosyalar için uygun yol belirtin Execute yöntem.

    set objBL = CreateObject("SQLXMLBulkLoad.SQLXMLBulkload.4.0")
    objBL.ConnectionString = "provider=SQLOLEDB;data source=localhost;database=tempdb;integrated security=SSPI"
    objBL.ErrorLogFile = "c:\error.log"
    objBL.CheckConstraints = True
    objBL.Execute "SampleSchema.xml", "SampleXMLData.xml"
    set objBL=Nothing
    
  5. yürütmek VBScript kodu.

Bu, eşdeğer XDR şeması oluşur:

<?xml version="1.0" ?>
<Schema xmlns="urn:schemas-microsoft-com:xml-data" 
        xmlns:dt="urn:schemas-microsoft-com:xml:datatypes"  
        xmlns:sql="urn:schemas-microsoft-com:xml-sql" >

    <ElementType name="Order" sql:relation="CustOrder" >
      <AttributeType name="OrderID" />
      <AttributeType name="CustomerID" />
      <attribute type="OrderID" />
      <attribute type="CustomerID" />
    </ElementType>

   <ElementType name="CustomerID" dt:type="int" />
   <ElementType name="CompanyName" dt:type="string" />
   <ElementType name="City" dt:type="string" />

   <ElementType name="root" sql:is-constant="1">
      <element type="Customers" />
   </ElementType>

   <ElementType name="Customers" sql:relation="Cust" 
                       sql:overflow-field="OverflowColumn"  >
      <element type="CustomerID" sql:field="CustomerID" />
      <element type="CompanyName" sql:field="CompanyName" />
      <element type="City" sql:field="City" />
      <element type="Order" >
             <sql:relationship
                key-relation="Cust"
                key="CustomerID"
                foreign-key="CustomerID"
                foreign-relation="CustOrder" />
      </element>
   </ElementType>
</Schema>

h.Dosyayı belirtme yol işlem modunda geçici dosyalar için

Toplu yükleme işlem modunda olduğunda (yani, Transaction özelliği TRUE olarak küme), de ayarlamalısınız TempFilePath özellik aşağıdaki koşullardan biri doğru olduğunda:

  • Toplu yükleme için bir uzak sunucuda var.

  • Bir başka bir yerel sürücü veya klasörü (bir TEMP ortam değişkeni tarafından belirtilen yolun dışında) kullanmak istediğiniz işlem modunda oluşturulan geçici dosyaları depolamak için.

Örneğin, aşağıdaki VBScript kodu toplu veri SampleXMLData.xml dosyasından işlem modunda Veritabanı tablolara yükler.The TempFilePath özellik is specified to küme the yol for the temporary files that are generated in transaction mode.

set objBL = CreateObject("SQLXMLBulkLoad.SQLXMLBulkload.4.0")
objBL.ConnectionString = "provider=SQLOLEDB;data source=localhost;database=tempdb;integrated security=SSPI"
objBL.ErrorLogFile = "c:\error.log"
objBL.CheckConstraints = True
objBL.Transaction=True
objBL.TempFilePath="\\Server\MyDir"
objBL.Execute "SampleSchema.xml", "SampleXMLData.xml"
set objBL=Nothing

Not

Geçici dosya yol hizmet hesabına hedef örneğinin erişebileceğiniz paylaşılan bir konumda olması gerekir SQL Server ve toplu yükleme uygulamanın çalıştığı hesaba. Geçici dosya yol, bir yerel sunucuda toplu yükleme olmadıkça, bir UNC yol (örneğin, \\sunucuadı\paylaşımadı) olması gerekir.

Bir çalışan örneği sınamak için

  1. Bu tablo oluşturma tempdb veritabanı:

    USE tempdb
    CREATE TABLE Cust (     CustomerID uniqueidentifier, 
          LastName  varchar(20))
    GO
    
  2. Tercih edilen metin veya XML Düzenleyicisi bir dosya oluşturun ve SampleSchema.xml kaydedin.Aşağıdaki XSD şeması dosyaya ekleyin:

    <xsd:schema xmlns:xsd="http://www.w3.org/2001/XMLSchema"
                xmlns:sql="urn:schemas-microsoft-com:mapping-schema">
      <xsd:element name="ROOT" sql:is-constant="true" >
        <xsd:complexType>
          <xsd:sequence>
            <xsd:element ref="Customers" />
          </xsd:sequence>
        </xsd:complexType>
      </xsd:element>
    
      <xsd:element name="Customers" sql:relation="Cust" >
       <xsd:complexType>
         <xsd:attribute name="CustomerID"  type="xsd:string" />
         <xsd:attribute name="LastName" type="xsd:string" />
       </xsd:complexType>
      </xsd:element>
    </xsd:schema>
    
  3. Tercih edilen metin veya XML Düzenleyicisi bir dosya oluşturun ve SampleXMLData.xml kaydedin.Aşağıdaki XML belgesi için dosyaya ekleyin:

    <ROOT>
    <Customers CustomerID="6F9619FF-8B86-D011-B42D-00C04FC964FF" 
               LastName="Smith" />
    </ROOT>
    
  4. Tercih edilen metin veya XML Düzenleyicisi bir dosya oluşturun ve ValidateAndBulkload.vbs kaydedin.Bu dosya için aşağıdaki VBScript kodu ekleyin.Uygun sunucu ve veritabanı adı sağlamak için bağlantı dizesi değiştirin.Parametre için belirtilen dosyalar için uygun yol belirtin Execute yöntem. Ayrıca uygun yol belirtmek TempFilePath Özellik.

    set objBL = CreateObject("SQLXMLBulkLoad.SQLXMLBulkload.4.0")
    objBL.ConnectionString = "provider=SQLOLEDB;data source=localhost;database=tempdb;integrated security=SSPI"
    objBL.ErrorLogFile = "c:\error.log"
    objBL.CheckConstraints = True
    objBL.Transaction=True
    objBL.TempFilePath="\\server\folder"
    objBL.Execute "SampleSchema.xml", "SampleXMLData.xml"
    set objBL=Nothing
    
  5. yürütmek VBScript kodu.

    Buna karşılık gelen şema belirtmelisiniz sql:datatype için MüşteriNo özniteliğini, değeri MüşteriNo gibi küme ayraçları ({ve}), örneğin içeren bir GUID olarak belirtilen:

    <ROOT>
    <Customers CustomerID="{6F9619FF-8B86-D011-B42D-00C04FC964FF}" 
               LastName="Smith" />
    </ROOT>
    

    Bu, güncelleştirilmiş şemayı oluşur:

    <xsd:schema xmlns:xsd="http://www.w3.org/2001/XMLSchema"
                xmlns:sql="urn:schemas-microsoft-com:mapping-schema">
      <xsd:element name="ROOT" sql:is-constant="true" >
        <xsd:complexType>
          <xsd:sequence>
            <xsd:element ref="Customers" />
          </xsd:sequence>
        </xsd:complexType>
      </xsd:element>
    
      <xsd:element name="Customers" sql:relation="Cust" >
       <xsd:complexType>
         <xsd:attribute name="CustomerID"  type="xsd:string" 
                        sql:datatype="uniqueidentifier" />
         <xsd:attribute name="LastName" type="xsd:string" />
       </xsd:complexType>
      </xsd:element>
    </xsd:schema>
    

    Ne zaman sql:datatype sütun tipi olarak tanımlayan belirtildi uniqueidentifier, ayraçları toplu yükleme işlemi kaldırır ({}) gelen ve giden MüşteriNo değeri sütun eklemeden önce.

Bu, eşdeğer XDR şeması oluşur:

<?xml version="1.0" ?>
<Schema xmlns="urn:schemas-microsoft-com:xml-data" 
        xmlns:dt="urn:schemas-microsoft-com:datatypes"  
        xmlns:sql="urn:schemas-microsoft-com:xml-sql" >
<ElementType name="ROOT" sql:is-constant="1">
      <element type="Customers" />
</ElementType>
<ElementType name="Customers" sql:relation="Cust" >
  <AttributeType name="CustomerID"  sql:datatype="uniqueidentifier" />
  <AttributeType name="LastName"   />

  <attribute type="CustomerID" />
  <attribute type="LastName"   />
</ElementType>
</Schema>

İ.Varolan veritabanı bağlantısını ConnectionCommand özellik ile kullanma

Toplu yükleme XML için varolan bir ADO bağlantısını kullanabilirsiniz.Bu XML toplu yükleme tek bir veri kaynağı üzerinde gerçekleştirilecek pek çok işlem kullanışlıdır.

The ConnectionCommand özellik enables you to use an existing ADO connection by using an ADO command object. Bu, Visual Basic aşağıdaki örnekte gösterilmiştir:

Private Sub Form_Load()
Dim objBL As New SQLXMLBulkLoad4
Dim objCmd As New ADODB.Command
Dim objConn As New ADODB.Connection

'Open a connection to an instance of SQL Server.
objConn.Open "provider=SQLOLEDB;data source=(local);database=tempdb;integrated security=SSPI"
'Ask the Command object to use the connection just established.
Set objCmd.ActiveConnection = objConn

'Tell Bulk Load to use the active command object that is using the Connection obj.
objBL.ConnectionCommand = objCmd
objBL.ErrorLogFile = "c:\error.log"
objBL.CheckConstraints = True
'The Transaction property must be set to True if you use ConnectionCommand.
objBL.Transaction = True
objBL.Execute "SampleSchema.xml", "SampleXMLData.xml"
Set objBL = Nothing
End Sub

Bir çalışan örneği sınamak için

  1. Iki tablo oluşturun. tempdb veritabanı:

    USE tempdb
    CREATE TABLE Cust(
                   CustomerID   varchar(5) PRIMARY KEY,
                   CompanyName  varchar(30),
                   City         varchar(20))
    GO
    CREATE TABLE CustOrder(
                   CustomerID  varchar(5) references Cust (CustomerID),
                   OrderID     varchar(5) PRIMARY KEY)
    GO
    
  2. Tercih edilen metin veya XML Düzenleyicisi bir dosya oluşturun ve SampleSchema.xml kaydedin.Aşağıdaki XSD şeması dosyaya ekleyin:

    <xsd:schema xmlns:xsd="http://www.w3.org/2001/XMLSchema"
                xmlns:sql="urn:schemas-microsoft-com:mapping-schema">
    <xsd:annotation>
      <xsd:appinfo>
        <sql:relationship name="CustCustOrder"
              parent="Cust"
              parent-key="CustomerID"
              child="CustOrder"
              child-key="CustomerID" />
      </xsd:appinfo>
    </xsd:annotation>
      <xsd:element name="ROOT" sql:is-constant="true" >
        <xsd:complexType>
          <xsd:sequence>
            <xsd:element ref="Customers" />
          </xsd:sequence>
        </xsd:complexType>
      </xsd:element>
      <xsd:element name="Customers" sql:relation="Cust" >
       <xsd:complexType>
         <xsd:sequence>
           <xsd:element name="CustomerID"  type="xsd:integer" />
           <xsd:element name="CompanyName" type="xsd:string" />
           <xsd:element name="City"        type="xsd:string" />
           <xsd:element name="Order" 
                              sql:relation="CustOrder"
                              sql:relationship="CustCustOrder" >
             <xsd:complexType>
              <xsd:attribute name="OrderID" type="xsd:integer" />
              <xsd:attribute name="CustomerID" type="xsd:integer" />
             </xsd:complexType>
           </xsd:element>
         </xsd:sequence>
        </xsd:complexType>
      </xsd:element>
    </xsd:schema>
    
  3. Tercih edilen metin veya XML Düzenleyicisi bir dosya oluşturun ve SampleXMLData.xml kaydedin.Aşağıdaki XML belgesi için dosyaya ekleyin:

    <ROOT>
      <Customers>
        <CustomerID>1111</CustomerID>
        <CompanyName>Hanari Carnes</CompanyName>
        <City>NY</City>
        <Order OrderID="1" />
        <Order OrderID="2" />
      </Customers>
    
      <Customers>
        <CustomerID>1112</CustomerID>
        <CompanyName>Toms Spezialitten</CompanyName>
         <City>LA</City>
        <Order OrderID="3" />
      </Customers>
      <Customers>
        <CustomerID>1113</CustomerID>
        <CompanyName>Victuailles en stock</CompanyName>
        <Order OrderID="4" />
    </Customers>
    </ROOT>
    
  4. Önceki kod bir Visual Basic (standart exe DOSYASı) uygulama oluşturur.Bu projeye başvuruda ekleyin:

    Microsoft XML BulkLoad for SQL Server 4.0 Type Library
    Microsoft ActiveX Data objects 2.6 Library
    
  5. Uygulama yürütmek.

Bu, eşdeğer XDR şeması oluşur:

<?xml version="1.0" ?>
<Schema xmlns="urn:schemas-microsoft-com:xml-data" 
        xmlns:dt="urn:schemas-microsoft-com:xml:datatypes"  
        xmlns:sql="urn:schemas-microsoft-com:xml-sql" >

   <ElementType name="CustomerID" dt:type="int" />
   <ElementType name="CompanyName" dt:type="string" />
   <ElementType name="City" dt:type="string" />

   <ElementType name="root" sql:is-constant="1">
      <element type="Customers" />
   </ElementType>

   <ElementType name="Customers" sql:relation="Cust"  >
      <element type="CustomerID" sql:field="CustomerID" />
      <element type="CompanyName" sql:field="CompanyName" />
      <element type="City" sql:field="City" />
      <element type="Order" >
         <sql:relationship
                key-relation="Cust"
                key="CustomerID"
                foreign-key="CustomerID"
                foreign-relation="CustOrder" />
      </element>
   </ElementType>
    <ElementType name="Order" sql:relation="CustOrder" >
      <AttributeType name="OrderID" />
      <AttributeType name="CustomerID" />
      <attribute type="OrderID" />
      <attribute type="CustomerID" />
    </ElementType>
</Schema>

j.Toplu olarak XML veri türü sütun yükleniyor

Eşleme şemada belirtirse bir XML veri türü kullanarak sütundakisql:datatype="xml" Ek açıklamayı XML toplu yükleme, XML alt öğeler için eşlenmiş alan kaynak belgeden bu sütuna kopyalayabilirsiniz.

Örnek AdventureWorks veritabanındaki Production.ProductModel Tablo görünümünü eşleştiren aşağıdaki XSD şeması göz önünde bulundurun.Bu tabloda CatalogDescription alan xml veri türü için eşlenen bir <Aza> öğe kullanarak sql:field ve sql:datatype="xml" ek açıklamalar.

<?xml version="1.0" encoding="utf-8" ?>
<xsd:schema xmlns:xsd="http://www.w3.org/2001/XMLSchema" 
           xmlns:sql="urn:schemas-microsoft-com:mapping-schema"
           xmlns="https://schemas.microsoft.com/sqlserver/2004/07/adventure-works/ProductModelDescription"> 
  <xsd:element name="ProductModel"  sql:relation="Production.ProductModel" >
    <xsd:complexType>
      <xsd:sequence>
        <xsd:element name="Name" type="xs:string"></xsd:element>
        <xsd:element name="Desc" sql:field="CatalogDescription" sql:datatype="xml">
        <xsd:complexType>
          <xsd:sequence>
            <xsd:element name="ProductDescription">
              <xsd:complexType>
                <xsd:sequence>
                  <xsd:element name="Summary" type="xs:anyType"/>
                </xsd:sequence>
              </xsd:complexType>
            </xsd:element>
          </xsd:sequence>
        </xsd:complexType>
        </xsd:element> 
     </xsd:sequence>
     <xsd:attribute name="ProductModelID" sql:field="ProductModelID" />
    </xsd:complexType>
  </xsd:element>
</xsd:schema>

Bir çalışan örneği sınamak için

  1. AdventureWorks örnek veritabanı'nın yüklü olduğunu doğrulayın.

    Daha fazla bilgi için bkz:AdventureWorks örnek veritabanları.

  2. Tercih edilen metin veya XML Düzenleyicisi bir dosya oluşturun ve SampleSchema.xml kaydedin.Yukarıdaki XSD şeması kopyalamak ve bunu bir dosyaya yapıştırın ve kaydedin.

  3. Tercih edilen metin veya XML Düzenleyicisi bir dosya oluşturun ve SampleXMLData.xml kaydedin.Aşağıdaki şu XML belgesini kopyalamanız ve bunu bir dosyaya yapıştırın ve sonra da aynı klasörde için önceki adımı yeniden kullanıldı olarak kaydedin.

    <ProductModel ProductModelID="2005">
        <Name>Mountain-100 (2005 model)</Name>
        <Desc><?xml-stylesheet href="ProductDescription.xsl" type="text/xsl"?>
            <p1:ProductDescription xmlns:p1="https://schemas.microsoft.com/sqlserver/2004/07/adventure-works/ProductModelDescription" 
                  xmlns:wm="https://schemas.microsoft.com/sqlserver/2004/07/adventure-works/ProductModelWarrAndMain" 
                  xmlns:wf="https://www.adventure-works.com/schemas/OtherFeatures" 
                  xmlns:html="http://www.w3.org/1999/xhtml" 
                  >
                <p1:Summary>
                    <html:p>Our top-of-the-line competition mountain bike. 
          Performance-enhancing options include the innovative HL Frame, 
          super-smooth front suspension, and traction for all terrain.
                            </html:p>
                </p1:Summary>
                <p1:Manufacturer>
                    <p1:Name>AdventureWorks</p1:Name>
                    <p1:Copyright>2002-2005</p1:Copyright>
                    <p1:ProductURL>HTTP://www.Adventure-works.com</p1:ProductURL>
                </p1:Manufacturer>
                <p1:Features>These are the product highlights. 
                     <wm:Warranty>
                        <wm:WarrantyPeriod>3 years</wm:WarrantyPeriod>
                        <wm:Description>parts and labor</wm:Description>
                    </wm:Warranty><wm:Maintenance>
                        <wm:NoOfYears>10 years</wm:NoOfYears>
                        <wm:Description>maintenance contract available through your dealer or any AdventureWorks retail store.</wm:Description>
                    </wm:Maintenance><wf:wheel>High performance wheels.</wf:wheel><wf:saddle>
                        <html:i>Anatomic design</html:i> and made from durable leather for a full-day of riding in comfort.</wf:saddle><wf:pedal>
                        <html:b>Top-of-the-line</html:b> clipless pedals with adjustable tension.</wf:pedal><wf:BikeFrame>Each frame is hand-crafted in our Bothell facility to the optimum diameter 
          and wall-thickness required of a premium mountain frame. 
          The heat-treated welded aluminum frame has a larger diameter tube that absorbs the bumps.</wf:BikeFrame><wf:crankset> Triple crankset; alumunim crank arm; flawless shifting. </wf:crankset></p1:Features>
                <!-- add one or more of these elements... one for each specific product in this product model -->
                <p1:Picture>
                    <p1:Angle>front</p1:Angle>
                    <p1:Size>small</p1:Size>
                    <p1:ProductPhotoID>118</p1:ProductPhotoID>
                </p1:Picture>
                <!-- add any tags in <specifications> -->
                <p1:Specifications> These are the product specifications.
                       <Material>Almuminum Alloy</Material><Color>Available in most colors</Color><ProductLine>Mountain bike</ProductLine><Style>Unisex</Style><RiderExperience>Advanced to Professional riders</RiderExperience></p1:Specifications>
            </p1:ProductDescription>
        </Desc>
    </ProductModel>
    
  4. Tercih edilen metin veya XML Düzenleyicisi bir dosya oluşturun ve BulkloadXml.vbs kaydedin.Aşağıdaki VBScript kodu kopyalayıp, dosyaya yapıştırın.Önceki XML veri ve şema dosyalarının için kullanılan gibi aynı klasöre kaydedin.

    set objBL = CreateObject("SQLXMLBulkLoad.SQLXMLBulkload.4.0")
    objBL.ConnectionString = "provider=SQLOLEDB;data source=MyServer;database=AdventureWorks;integrated security=SSPI"
    
    Dim fso, sAppPath
    Set fso = CreateObject("Scripting.FileSystemObject") 
    sAppPath = fso.GetFolder(".") 
    
    objBL.ErrorLogFile = sAppPath & "\error.log"
    
    'Execute XML bulkload using file.
    objBL.Execute "SampleSchema.xml", "SampleXMLData.xml"
    set objBL=Nothing
    
  5. BulkloadXml.vbs komut dosyasını yürütün.