第一為原始資料表
第二為比較資料表
第三為結果資料表
程式碼擷圖
以下為程式碼
Public Function CompareDataTables(ByVal first As DataTable, ByVal second As DataTable) As DataTable
first.TableName = "FirstTable"
second.TableName = "SecondTable"
Dim table As New DataTable("Difference")
Using ds As New DataSet()
ds.Tables.AddRange(New DataTable() {first.Copy(), second.Copy()})
Dim firstcolumns As DataColumn() = New DataColumn(ds.Tables(0).Columns.Count - 1) {}
For i As Integer = 0 To firstcolumns.Length - 1
firstcolumns(i) = ds.Tables(0).Columns(i)
Next
Dim secondcolumns As DataColumn() = New DataColumn(ds.Tables(1).Columns.Count - 1) {}
For i As Integer = 0 To secondcolumns.Length - 1
secondcolumns(i) = ds.Tables(1).Columns(i)
Next
Dim r As New DataRelation(String.Empty, firstcolumns, secondcolumns, False)
ds.Relations.Add(r)
For i As Integer = 0 To first.Columns.Count - 1
table.Columns.Add(first.Columns(i).ColumnName, first.Columns(i).DataType)
Next
table.BeginLoadData()
For Each parentrow As DataRow In ds.Tables(0).Rows
Dim childrows As DataRow() = parentrow.GetChildRows(r)
If childrows Is Nothing OrElse childrows.Length = 0 Then
table.LoadDataRow(parentrow.ItemArray, True)
End If
Next
table.EndLoadData()
End Using
Return table
End Function
first.TableName = "FirstTable"
second.TableName = "SecondTable"
Dim table As New DataTable("Difference")
Using ds As New DataSet()
ds.Tables.AddRange(New DataTable() {first.Copy(), second.Copy()})
Dim firstcolumns As DataColumn() = New DataColumn(ds.Tables(0).Columns.Count - 1) {}
For i As Integer = 0 To firstcolumns.Length - 1
firstcolumns(i) = ds.Tables(0).Columns(i)
Next
Dim secondcolumns As DataColumn() = New DataColumn(ds.Tables(1).Columns.Count - 1) {}
For i As Integer = 0 To secondcolumns.Length - 1
secondcolumns(i) = ds.Tables(1).Columns(i)
Next
Dim r As New DataRelation(String.Empty, firstcolumns, secondcolumns, False)
ds.Relations.Add(r)
For i As Integer = 0 To first.Columns.Count - 1
table.Columns.Add(first.Columns(i).ColumnName, first.Columns(i).DataType)
Next
table.BeginLoadData()
For Each parentrow As DataRow In ds.Tables(0).Rows
Dim childrows As DataRow() = parentrow.GetChildRows(r)
If childrows Is Nothing OrElse childrows.Length = 0 Then
table.LoadDataRow(parentrow.ItemArray, True)
End If
Next
table.EndLoadData()
End Using
Return table
End Function
程式檔案下載(vb.net 2010)
請問千山大大:
回覆刪除如果firstcolumns 的欄位超過32,就發生「無法擁有超過 32 個資料行」的錯誤訊息,請問這個部份有解嗎??
小舖上我有回應你的問題了 #3
回覆刪除http://www.blueshop.com.tw/board/FUM20050124191756KKC/BRD201206162257147HX.html
小琳版主也有針對你的問題回答
請參考那些國外網站的論壇