Im working on a dotnet project wherein the task is to compare 2 tables which are copy of each other, table1[old] and table1_copy[new] as of now im using a ‘for loop’ and comparing the 2 tables based on primary key row by row.
*The above approach is quite slow as there are nearly 13lakhs rows in a table.
So suggest a fast approach to do the same.
*
Below is my used approach.
static void CompareTables(string connectionString, string tableName1, string tableName2, string primaryKeyColumn)
{
using (SqlConnection connection = new SqlConnection(connectionString))
{
try
{
connection.Open();
Console.WriteLine();
Console.WriteLine("Connection Opened!");
// Load data from both tables into a DataSet
DataSet ds = new DataSet();
Console.WriteLine($"Comparing {tableName1} and {tableName2}");
SqlDataAdapter adapter1 = new SqlDataAdapter($"SELECT * FROM {tableName1}", connection);
adapter1.Fill(ds, tableName1);
SqlDataAdapter adapter2 = new SqlDataAdapter($"SELECT * FROM {tableName2}", connection);
adapter2.Fill(ds, tableName2);
DataTable dtOriginal = ds.Tables[tableName1];
DataTable dtCopy = ds.Tables[tableName2];
// Create a dictionary to store the original table data for quick lookup
// Dictionary<object, DataRow> originalTableDict = new Dictionary<object, DataRow>();
// foreach (DataRow row in dtOriginal.Rows)
// {
// originalTableDict[row[primaryKeyColumn]] = row;
// }
bool changesFound = false;
foreach (DataRow rowCopy in dtCopy.Rows)
{
DataRow[] originalRows = dtOriginal.Select($"{primaryKeyColumn} = {rowCopy[primaryKeyColumn]}");
if (originalRows.Length > 0)
{
DataRow rowOriginal = originalRows[0];
for (int i = 0; i < dtOriginal.Columns.Count; i++)
{
string columnName = dtOriginal.Columns[i].ColumnName;
object originalValue = rowOriginal[columnName];
object copyValue = rowCopy[columnName];
if (!Equals(originalValue, copyValue))
{
if (!changesFound)
{
changesFound = true;
Console.WriteLine("Changes found:");
}
Console.WriteLine($"Row ID: {rowOriginal[primaryKeyColumn]}, Column: {columnName}, Original: {originalValue}, Updated: {copyValue}");
}
}
}
}
New contributor
Madara18 is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.