使用SqlBulkCopy复制存储的proc的结果,该结果返回多个数据集

时间:2018-11-13 11:27:28

标签: sql vb.net

我有一个存储的proc,它返回两组不同的结果(标题和详细信息)。然后,我想获取这些结果集,并将它们独立地写入两个目标表中。每个结果集的格式与相应的目标表相同,因此SqlBulkCopy似乎是理想的解决方案。代码如下:

Try
    Using connection As SqlConnection = New SqlConnection(My.Settings.MyConnectionString)
        Dim sqlQuery As String = "exec sp_get_order_batch @BatchSize, @NewBatchId"
        connection.Open()

        Using comm As SqlCommand = New SqlCommand(sqlQuery, connection)
            comm.Parameters.Add("@BatchSize", SqlDbType.Int).Value = Me.Config.BatchSize
            comm.Parameters.Add("@NewBatchId", SqlDbType.Int).Value = Me.Config.GetNewBatchNumber()

            Dim rs As SqlDataReader = comm.ExecuteReader
            Dim dtHeader As DataTable = New DataTable
            dtHeader.Load(rs)

            If dtHeader.Rows.Count >= 1 Then
                'We've got some data back - yippee.

                'Write the header data out to the holding table
                Using sqlBulkCopyHeader As New SqlBulkCopy(connection)
                    sqlBulkCopyHeader.DestinationTableName = "dbo.web_order_header"
                    Try
                        sqlBulkCopyHeader.WriteToServer(rs)
                    Catch ex As Exception
                        Me.EventLog1.WriteEntry(ex.Message)
                    End Try
                End Using

                'Grab the line data out as well...
                rs.NextResult()
                Dim dtLines As DataTable = New DataTable
                dtLines.Load(rs)

                'Write the line data out to the holding table
                Using sqlBulkCopyLines As New SqlBulkCopy(connection)
                    sqlBulkCopyLines.DestinationTableName = "dbo.web_order_lines"
                    Try
                        sqlBulkCopyLines.WriteToServer(rs)
                    Catch ex As Exception
                        Me.EventLog1.WriteEntry(ex.Message)
                    End Try
                End Using

            End If

        End Using
    End Using

Catch ex As Exception
    Me.EventLog1.WriteEntry(ex.Message)
End Try

但是,实际上发生的是对SqlBulkCopy的第一个调用实际上是在尝试将seconf结果集写入目标表,而不是第一个。

是否有一种方法可以实现我想要的功能,而不必求助于重复每个数据集中的行并一次写入它们?

0 个答案:

没有答案