Поделиться через


Выполнение диаграммы обновления при помощи ADO (SQLXML 4.0)

Следующее приложение на языке Microsoft Visual Basic использует ADO для установки соединения с экземпляром Microsoft SQL Server и выполняет диаграмму обновления. Диаграмма обновления изменяет фамилию конкретного сотрудника. В данном примере используется образец базы данных База данных AdventureWorks2008R2.

В этом образце приложения происходит следующее.

  • Объект conn (ADODB.Connection) устанавливает соединение с выполняющимся экземпляром SQL Server на заданном сервере.

  • Объект cmd (ADODB.Command) выполняется для установленного соединения.

  • В качестве диалекта команды задано значение DBGUID_MSSQLXML.

  • Диаграмма обновления копируется в поток команды (strmIn).

  • Выходной поток команды установлен в объект StrmOut (ADODB.Stream), который получает все возвращенные данные.

  • Наконец выполняется команда (диаграмма обновления).

Ниже представлен образец кода.

Private Sub Form_Load()

  Dim cmd As New ADODB.Command
  Dim conn As New ADODB.Connection
  Dim strmIn As New ADODB.Stream
  Dim strmOut As New ADODB.Stream
  Dim SQLxml As String

  ' Open a connection to the instance of SQL Server.
  conn.Provider = "SQLOLEDB"
  conn.Open "server=(local); database=AdventureWorks2008R2; Integrated Security=SSPI; "
  conn.Properties("SQLXML Version") = "SQLXML.4.0"
  Set cmd.ActiveConnection = conn

  ' Build the command string in the form of an XML template.
    SQLxml = "<ROOT xmlns:updg='urn:schemas-microsoft-com:xml-updategram' >"
    SQLxml = SQLxml & "  <updg:sync updg:nullvalue='IsNULL'>"
    SQLxml = SQLxml & "    <updg:before>"
    SQLxml = SQLxml & "       <Person.Person BusinessEntityID='64' Title='IsNULL'/>"
    SQLxml = SQLxml & "    </updg:before>"
    SQLxml = SQLxml & "    <updg:after>"
    SQLxml = SQLxml & "       <Person.Person BusinessEntityID='64' Title='Mr.'/>"
    SQLxml = SQLxml & "    </updg:after>"
    SQLxml = SQLxml & "  </updg:sync>"
    SQLxml = SQLxml & "</ROOT>"

  ' Set the command dialect to DBGUID_MSSQLXML.
  cmd.Dialect = "{5d531cb2-e6ed-11d2-b252-00c04f681b71}"

  ' Open the command stream and write our template to it.
  strmIn.Open
  strmIn.WriteText SQLxml
  strmIn.Position = 0

  Set cmd.CommandStream = strmIn

  ' Execute the command, open the return stream, and read the result.
  strmOut.Open
  strmOut.LineSeparator = adCRLF
  cmd.Properties("Output Stream").Value = strmOut
  cmd.Properties("Output Encoding").Value = "UTF-8"
  cmd.Execute , , adExecuteStream
  strmOut.Position = 0
  Debug.Print strmOut.ReadText
  strmOut.Close
  strmIn.Close

End Sub
ПримечаниеПримечание

Если SQLXML используется из ADO для выполнения диаграмм обновления, которые задают схему XSD, в объекте соединения необходимо присвоить свойству SQLXML Version значение SQLXML.4.0, как показано в следующем примере кода.

conn.Properties("SQLXML Version") = "SQLXML.4.0"

Указание схемы сопоставления для диаграммы обновления

В этом примере показано, как задать и использовать схему сопоставления в диаграмме обновления.

Сохраните на диск следующую схему XSD (EmpSchema.xml) и убедитесь, что обновлен заданный в коде путь к расположению схемы сопоставления. Код предполагает, что схема сохранена на диске C: в папке Schemas.

<xsd:schema xmlns:xsd="http://www.w3.org/2001/XMLSchema"
            xmlns:sql="urn:schemas-microsoft-com:mapping-schema">
  <xsd:element name="Contact" sql:relation="Person.Person" >
   <xsd:complexType>
        <xsd:attribute name="CID"  
                       sql:field="BusinessEntityID" 
                       type="xsd:string" /> 
        <xsd:attribute name="MName"  
                       sql:field="MiddleName"  
                       type="xsd:string" />
    </xsd:complexType>
  </xsd:element>
</xsd:schema>

Поскольку можно задать как схему XSD, так и схему XDR, приводим эквивалентную схему XDR:

<?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="Contact" sql:relation="Person.Person" >
       <AttributeType name="CID" />
       <AttributeType name="MName" />

       <attribute type="CID" sql:field="BusinessEntityID" />
       <attribute type="MName" sql:field="MiddleName" />
     </ElementType>
   </Schema> 

Следующий код Visual Basic выполняет диаграмму обновления, связанную со схемой сопоставления. Диаграмма обновления изменяет отчество контакта 1 в таблице Person.Person.

Private Sub Form_Load()
    Dim cmd As New ADODB.Command
    Dim conn As New ADODB.Connection
    Dim strmIn As New ADODB.Stream
    Dim strmOut As New ADODB.Stream

    ' Open a connection to the SQL Server.
    conn.Provider = "SQLOLEDB"
    conn.Open "server=(local); database=AdventureWorks2008R2; Integrated Security='SSPI' ;"
    conn.Properties("SQLXML Version") = "SQLXML.4.0"
    Set cmd.ActiveConnection = conn
    
    ' Open the command stream and write the template to it.
    strmIn.Open
    strmIn.WriteText "<ROOT xmlns:updg='urn:schemas-microsoft-com:xml-updategram' >"
    strmIn.WriteText "  <updg:sync mapping-schema='C:\Schemas\EmpSchema.xml' >"
    strmIn.WriteText "      <updg:before>"
    strmIn.WriteText "          <Contact CID='1' />"
    strmIn.WriteText "      </updg:before>"
    strmIn.WriteText "      <updg:after>"
    strmIn.WriteText "          <Contact MName='M.'/>"
    strmIn.WriteText "      </updg:after>"
    strmIn.WriteText "  </updg:sync>"
    strmIn.WriteText "</ROOT>"
    
    ' Set the command dialect to XML.
    cmd.Dialect = "{5d531cb2-e6ed-11d2-b252-00c04f681b71}"
    strmIn.Position = 0
    Set cmd.CommandStream = strmIn
 
    ' Execute the command, open the return stream, and read the result.
    strmOut.Open
    strmOut.LineSeparator = adCRLF
    cmd.Properties("Output Stream").Value = strmOut
    cmd.Execute , , adExecuteStream
    strmOut.Position = 0
    Debug.Print strmOut.ReadText
    strmOut.Close
    strmIn.Close
    conn.Close
End Sub

Передача параметров

В представленных выше приложениях Visual Basic отсутствует передача параметров. В следующем приложении в диаграмму обновления передаются значения BusinessEntityID и MiddleName в качестве параметризованного входа.

Private Sub Form_Load()
  
  Dim cmd As New ADODB.Command
  Dim conn As New ADODB.Connection
  Dim strmIn As New ADODB.Stream
  Dim strmOut As New ADODB.Stream
  Dim InputBusinessEntityID As String
  Dim InputMiddleName As String

  InputBusinessEntityID = "1"
  InputMiddleName = "Q."

  ' Open a connection to the instance of SQL Server.
  conn.Provider = "SQLOLEDB"
  conn.Open "server=(local); database=AdventureWorks2008R2; Integrated Security=SSPI; "
  conn.Properties("SQLXML Version") = "SQLXML.4.0"
  Set cmd.ActiveConnection = conn

  ' Build the command string in the form of an XML template.
  SQLxml = "<ROOT xmlns:updg='urn:schemas-microsoft-com:xml-updategram' >"
  SQLxml = SQLxml & "<updg:header>"
  SQLxml = SQLxml & "<updg:param name='BusinessEntityID'/>"
  SQLxml = SQLxml & "<updg:param name='MiddleName' />"
  SQLxml = SQLxml & "</updg:header>"
  SQLxml = SQLxml & "<updg:sync >"
  SQLxml = SQLxml & " <updg:before>"
  SQLxml = SQLxml & "   <Person.Person BusinessEntityID='$BusinessEntityID' />"
  SQLxml = SQLxml & "</updg:before>"
  SQLxml = SQLxml & "<updg:after>"
  SQLxml = SQLxml & "<Person.Person MiddleName='$MiddleName' />"
  SQLxml = SQLxml & "</updg:after>"
  SQLxml = SQLxml & "</updg:sync>"
  SQLxml = SQLxml & "</ROOT>"

  ' Set the command dialect to XML.
  cmd.Dialect = "{5d531cb2-e6ed-11d2-b252-00c04f681b71}"

  ' Open the command stream and write the template to it.
  strmIn.Open
  strmIn.WriteText SQLxml
  strmIn.Position = 0

  Set cmd.CommandStream = strmIn

  ' Execute the command, open the return stream, and read the result.
  strmOut.Open
  strmOut.LineSeparator = adCRLF
  cmd.NamedParameters = True
  cmd.Parameters.Append cmd.CreateParameter("@BusinessEntityID", adBSTR, adParamInput, 1, InputBusinessEntityID)
  cmd.Parameters.Append cmd.CreateParameter("@MiddleName", adBSTR, adParamInput, 7, InputMiddleName)
  cmd.Properties("Output Stream").Value = strmOut
  cmd.Execute , , adExecuteStream
  strmOut.Position = 0
  Debug.Print strmOut.ReadText

End Sub