0

我最近想出了如何使用 VB.Net 从 SQL Server 将数据导出为 XML。我使用三个 SQL 语句并标注一个 XPath 文档以将根标记添加到导出:

        Dim connectionString As String
        Dim connection As New SqlConnection
        Dim command As New SqlCommand()

        Dim sql = "select * from scheduledata for xml auto, elements " & _
        "select * from costdata for xml auto, elements " & _
        "select * from csintegrationdata for xml auto, elements "

        connectionString = "Data Source=(localdb)\v11.0; _ 
        Initial Catalog=localACETest;Integrated Security=True"
        connection = New SqlConnection(connectionString)
        connection.Open()

        command.CommandText = sql
        command.Connection = connection
        command.CommandType = CommandType.Text

        Dim xmlRead As XmlReader = command.ExecuteXmlReader()

        Dim xp As New XPath.XPathDocument(xmlRead)
        Dim xn As XPath.XPathNavigator = xp.CreateNavigator()
        Dim xd As New XmlDocument
        Dim root As XmlNode = xd.CreateElement("Data")
        root.InnerXml = xn.OuterXml
        xd.AppendChild(root)

        Dim fStream As New FileStream(Directory, FileMode.Create, FileAccess.ReadWrite)

        xd.Save(fStream)
        fStream.Close()

我希望能够使用 VB 将这些数据重新导入 SQL 表,但我遇到了一些麻烦。我正在使用的代码是这样的:

        Using sqlconn As New SqlConnection(connectionString)
            Dim ds As New DataSet()
            Dim sourcedata As New DataTable()
            Dim ii As Integer = 0
            ds.ReadXml("C:\Users\coopere.COOPERE-PC\Desktop\Test.xml")
            sqlconn.Open()

            Using bulkcopy As New SqlBulkCopy(sqlconn)
                sourcedata = ds.Tables(0)

                bulkcopy.DestinationTableName = "CSIntegrationData"
                bulkcopy.ColumnMappings.Add("Period", "Period")
                bulkcopy.ColumnMappings.Add("Program", "Program")
                bulkcopy.ColumnMappings.Add("CostControlAccount", "CostControlAccount")
                ...

                bulkcopy.WriteToServer(sourcedata)
            End Using
            sqlconn.Close()
        End Using

执行此操作时,出现错误:System.InvalidOperationException:给定的 ColumnName 'CostControlAccount' 与数据源中的任何列都不匹配。

我相信这是因为导出到 XML 的表之一有一个充满 NULL 值的列,这些值不会在 XML 的任何地方结束。但情况并非总是如此——通常情况下,会有价值观。

考虑到 SqlBulkCopy 的列映射无法处理接受空值,我如何在导出/导入中处理空值?我也对完全不同的路线持开放态度。

4

1 回答 1

1

经过大量挖掘,我找到了这个链接

作为 FOR XML 函数的一部分,您可以在最后附加 XSINIL以处理空值。生成的 XML 如下所示。

select * from TABLENAME for xml auto, elements XSINIL

<ScheduleWorkPackage xsi:nil="true" />
于 2013-07-23T19:25:26.333 回答