我最近想出了如何使用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的列映射无法处理接受空值,如何在导出/导入中处理空值?我也完全接受了不同的路线。
答案 0 :(得分:1)
经过多次挖掘,我找到了this link。
作为FOR XML功能的一部分,您可以在最后处理 XSINIL 以处理空值。生成的XML如下所示。
select * from TABLENAME for xml auto, elements XSINIL
<ScheduleWorkPackage xsi:nil="true" />