Compartilhar via


Executando um diagrama de atualização usando o ADO (SQLXML 4.0)

Este aplicativo Microsoft Visual Basic usa o ADO para estabelecer uma conexão com uma instância do Microsoft SQL Server e executar um diagrama de atualização. O diagrama de atualização atualiza o sobrenome de um funcionário específico. Este exemplo usa o banco de dados AdventureWorks de exemplo.

Neste aplicativo de exemplo:

  • O objeto conn (ADODB.Connection) estabelece uma conexão com uma instância do SQL Server em execução em um computador servidor específico.

  • O objeto cmd (ADODB.Command) é executado na conexão estabelecida.

  • O dialeto do comando é definido como DBGUID_MSSQLXML.

  • O diagrama de atualização é copiado para o fluxo de comando (strmIn).

  • O fluxo de saída do comando é definido como o objeto StrmOut (ADODB.Stream) para receber qualquer dado retornado.

  • Por fim, o comando (diagrama de atualização) é executado.

Segue o código de exemplo:

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=AdventureWorks; 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.Contact ContactID='64' Title='IsNULL'/>"
    SQLxml = SQLxml & "    </updg:before>"
    SQLxml = SQLxml & "    <updg:after>"
    SQLxml = SQLxml & "       <Person.Contact ContactID='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
ObservaçãoObservação

Se estiver usando o SQLXML do ADO para executar diagramas de atualização que especificam um esquema XSD, defina a propriedade "SQLXML Version" como "SQLXML.4.0" no objeto de conexão, como mostra a linha de código de exemplo a seguir:

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

Especificando um esquema de mapeamento para o diagrama de atualização

Este exemplo ilustra como especificar e usar um esquema de mapeamento em um diagrama de atualização.

Salve o seguinte esquema XSD (EmpSchema.xml) no disco e certifique-se de atualizar o caminho que é especificado no código para o local do esquema de mapeamento no disco. O código presume que o esquema é salvo na unidade C:, na pasta de 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.Contact" >
   <xsd:complexType>
        <xsd:attribute name="CID"  
                       sql:field="ContactID" 
                       type="xsd:string" /> 
        <xsd:attribute name="MName"  
                       sql:field="MiddleName"  
                       type="xsd:string" />
    </xsd:complexType>
  </xsd:element>
</xsd:schema>

Como é possível especificar esquemas XSD e XDR, este é o esquema XDR equivalente:

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

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

Este é o código do Visual Basic para executar um diagrama de atualização que tem um esquema de mapeamento associado. O diagrama de atualização atualiza o nome do meio do contato 1 na tabela Person.Contact.

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=AdventureWorks; 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

Passando parâmetros

Nos aplicativos do Visual Basic fornecidos anteriormente, os parâmetros não são passados. Neste aplicativo, os valores de ContactID e MiddleName são passados como uma entrada com parâmetros para o diagrama de atualização.

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 InputContactID As String
  Dim InputMiddleName As String

  InputContactID = "1"
  InputMiddleName = "Q."

  ' Open a connection to the instance of SQL Server.
  conn.Provider = "SQLOLEDB"
  conn.Open "server=(local); database=AdventureWorks; 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='ContactID'/>"
  SQLxml = SQLxml & "<updg:param name='MiddleName' />"
  SQLxml = SQLxml & "</updg:header>"
  SQLxml = SQLxml & "<updg:sync >"
  SQLxml = SQLxml & " <updg:before>"
  SQLxml = SQLxml & "   <Person.Contact ContactID='$ContactID' />"
  SQLxml = SQLxml & "</updg:before>"
  SQLxml = SQLxml & "<updg:after>"
  SQLxml = SQLxml & "<Person.Contact 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("@ContactID", adBSTR, adParamInput, 1, InputContactID)
  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