2010-05-19 186 views
1

我有多個我想合併爲一個的數據集。有一個公共ID字段可以關聯到每一行。在數據集上調用合併將爲數據集添加額外的行,但我想組合其他列。在一個查詢中有太多的字段需要這樣做,因此會使其無法管理。每個單獨的查詢將能夠處理排序以確保數據放置在正確的行中。將多個數據集列組合到一個數據集中

對於實例可以說我有導致兩個數據集的兩個查詢:

SELECT ID, colA, colB 
SELECT colC, colD 

得到的數據集看起來像

ID colA colB colC colD 
1 a b c d 
2 e f g h 

就如何做到這一點任何想法?

+0

這可能有所幫助:http://stackoverflow.com/questions/1259788/join-between-two-tables-with-linq-to-datasets – 2010-05-19 18:51:37

回答

1

這裏是一個如何使用ASP.NET和VB.NET實現你想要的例子。我爲你創建了一個「MergeColumns」和「MergeData」子。

Private Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load 
     'Create the dataset and put in the data. Normally you will just get this from a database query' 

     Dim ds1 As New Data.DataSet 
     Dim ds2 As New Data.DataSet 

     Dim dt1 = ds1.Tables.Add() 
     dt1.Columns.Add("ID", GetType(Int32)) 
     dt1.Columns.Add("ColA", GetType(String)) 
     dt1.Columns.Add("ColB", GetType(String)) 

     Dim dt2 = ds2.Tables.Add() 
     dt2.Columns.Add("ColC", GetType(String)) 
     dt2.Columns.Add("ColD", GetType(String)) 

     dt1.Rows.Add(1, "a", "b") 
     dt2.Rows.Add("c", "d") 
     dt1.Rows.Add(2, "e", "f") 
     dt2.Rows.Add("g", "h") 

     'Sample data created, now to merge the results like you want' 
     Dim dsNew As New Data.DataSet 
     Dim dtNew = dsNew.Tables.Add(0) 

     MergeColumns(dtNew, dt1, dt2) 
     MergeData(dtNew, dt1, dt2) 

     'Display the results' 
     dsNew.AcceptChanges() 
     Response.Write(dsNew.GetXml) 

    End Sub 


    Private Sub MergeColumns(ByVal TargetTable As Data.DataTable, ByVal ParamArray SourceTables() As Data.DataTable) 
     For Each dtSource In SourceTables 
      'Make a clone of the table, then steal the columns from the clone' 
      Dim dtClone = dtSource.Clone 

      While dtClone.Columns.Count > 0 
       Dim dc = dtClone.Columns(0) 

       dtClone.Columns.Remove(dc) 

       TargetTable.Columns.Add(dc) 
      End While 
     Next 
    End Sub 


    Private Sub MergeData(ByVal TargetTable As Data.DataTable, ByVal ParamArray SourceTables() As Data.DataTable) 
     'Determine the number of rows the final table will have' 
     Dim nMaxRowCount = 0 
     For Each dt In SourceTables 
      If dt.Rows.Count > nMaxRowCount Then 
       nMaxRowCount = dt.Rows.Count 
      End If 
     Next 

     For i = 0 To nMaxRowCount - 1 
      'Create a new row using column data from each table. Assumes the name is unique across tables.' 
      Dim drTarget = TargetTable.NewRow 
      For Each dcTarget As Data.DataColumn In TargetTable.Columns 
       For Each dt In SourceTables 
        If i < dt.Rows.Count AndAlso dt.Columns.Contains(dcTarget.ColumnName) Then 
         drTarget(dcTarget) = dt.Rows(i)(dcTarget.ColumnName) 
        End If 
       Next 
      Next 
      TargetTable.Rows.Add(drTarget) 
     Next 

    End Sub 
相關問題