Compartir a través de


Ejecutar un diagrama de actualización mediante ADO (SQLXML 4.0)

Esta aplicación de Microsoft Visual Basic utiliza ADO para establecer una conexión a una instancia de Microsoft SQL Server y ejecutar un diagrama de actualización. El diagrama de actualización actualiza el apellido de un empleado concreto. En este ejemplo se utiliza la base de datos de ejemplo AdventureWorks.

En esta aplicación de ejemplo:

  • El objeto conn (ADODB.Connection) establece una conexión a una instancia de SQL Server en ejecución en un equipo servidor determinado.

  • El objeto cmd (ADODB.Command) se ejecuta en la conexión establecida.

  • El lenguaje de comandos está establecido en DBGUID_MSSQLXML.

  • El diagrama de actualización se copia en el flujo de comandos (strmIn).

  • El flujo de salida del comando se establece en el objeto StrmOut (ADODB.Stream) para recibir cualquier dato devuelto.

  • Finalmente se ejecuta el comando (diagrama de actualización).

Éste es el código de ejemplo:

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

[!NOTA]

Si está utilizando SQLXML de ADO para ejecutar diagramas de actualización que especifican un esquema XSD, en el objeto de conexión debe establecer la propiedad "SQLXML Version" en "SQLXML.4.0", tal y como se muestra en la siguiente línea de código de ejemplo:

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

Especificar un esquema de asignación para el diagrama de actualización

En este ejemplo se muestra cómo especificar y utilizar un esquema de asignación en un diagrama de actualización.

Guarde el siguiente esquema XSD (EmpSchema.xml) en su disco y asegúrese de actualizar la ruta de acceso que se especifica en el código a la ubicación del esquema de asignación en su disco. El código supone que el esquema está guardado en la unidad C:, en la carpeta 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>

Puesto que se pueden especificar esquemas XSD y XDR, éste es el 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> 

Éste es el código de Visual Basic para ejecutar un diagrama de actualización que tiene un esquema de asignación asociado. El diagrama de actualización actualiza el segundo nombre del contacto 1 de la tabla 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

Pasar parámetros

En las aplicaciones Visual Basic proporcionadas anteriormente, los parámetros no se pasan. En esta aplicación, los valores MiddleName y el ContactID se pasan al diagrama de actualización como entrada parametrizada.

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