Public Function GetDifferencesBetweenTwoTables(ByVal DataTable1 As Data.DataTable, ByVal DataTable2 As Data.DataTable) As Data.DataTable
Debug.WriteLine("Looking for changed records.")
Debug.WriteLine("This function will compare two data tables and return a data table with the changed rows.")
Debug.WriteLine("The two tables must have the same columns and at least one key column.")
'Create an empty table with the correct fields to return the differences.
Dim ModifiedDataTable As Data.DataTable = DataTable1.Clone
'Create an array to store the names of the key columns.
Dim KeyColumnNames(DataTable1.PrimaryKey.Length - 1) As String
'Get the key column names from the first table.
For I As Integer = 0 To DataTable1.PrimaryKey.Length - 1
KeyColumnNames(I) = DataTable1.PrimaryKey(I).ColumnName
Next I
'Look at each row in the second table.
For Each RowInTable2 As Data.DataRow In DataTable2.Rows
'Create a flag to record if the rows are different or not.
Dim RowChanged As Boolean = False
'Create an array to store the key values.
Dim RowKeys(KeyColumnNames.Length - 1) As String
'Get the key values from the current row in the second table.
For I As Integer = 0 To RowKeys.Length - 1
RowKeys(I) = RowInTable2.Item(KeyColumnNames(I))
Next I
'Look for a row in the first table that matches the current row in the second table.
Dim RowInTable1 As Data.DataRow = DataTable1.Rows.Find(RowKeys)
'If a match was found...
If RowInTable1 IsNot Nothing Then
'Look at each column.
For Each ColumnInTable1 As Data.DataColumn In DataTable1.Columns
'Get the column number
Dim ColumnIndex As Integer = ColumnInTable1.Ordinal
'Figure out what type of data is in the column.
Dim ColumnType As Type = ColumnInTable1.DataType
'Compair the cell of this column in both of the rows to see if they match.
'The cells must be converted to the correct type before comparison because nulls will cause it to fail.
If Convert.ChangeType(RowInTable1.Item(ColumnIndex), ColumnType) <> Convert.ChangeType(RowInTable2.Item(ColumnIndex), ColumnType) Then
'The cells do not match, so flag the change.
RowChanged = True
'No use looking at the rest of the cells, so leave the for/next loop.
Exit For
End If
Next ColumnInTable1
Else
'The row in the second table does not exist in the first table so add this row to the table of modified rows.
RowChanged = True
End If
If RowChanged = True Then
'Something in the current row was changed, so add it to the table to be returned by this function.
ModifiedDataTable.Rows.Add(RowInTable2.ItemArray)
End If
Next RowInTable2
Debug.WriteLine(ModifiedDataTable.Rows.Count & " records were changed.")
Return ModifiedDataTable
End Function
Tips and tricks for .NET using ASP and VB code.
Get the differences between two data tables.
Subscribe to:
Post Comments (Atom)
No comments:
Post a Comment