Link to home
Start Free TrialLog in
Avatar of Sandiya

asked on

Urgent :compare two datatables

Hi All,

I want a code tocheck all columns of Source table and see if they exist in Target table. If they dont exist then i want to add the columns in the target table.The source table comes from salesforce and the target table is in sql server.

I just want a code to identify the missing columns and suggest the user to create the column in the target.
Avatar of Kamal Khaleefa
Kamal Khaleefa
Flag of Kuwait image


i recommend the following

dim dt1 as new datattable=get data from course in db1
dim dt2 as new datattable=get data from course in db2

then write a for loop to compare the columns name
ex: for i as integer=0 to dt1. Columns.Count -1 ...
and then u can know what is the missing
and base on that create a sql statement to do the necessary modification and execute it
Avatar of Sandiya



Can u please explain the logic to compare column names between 2 datatable

Avatar of Dirk Haest
You can use linq. Small example attached.

The last query will tell you that you have a column (namely state) in your second datatable that is not in your first datatable

 Private Sub compareTables()
        Dim Table1 As DataTable = New DataTable("Customers")
        Table1.Columns.Add("Name", Type.GetType("System.String"))
        Table1.Columns.Add("Firstname", Type.GetType("System.String"))
        Table1.Columns.Add("Street", Type.GetType("System.String"))
        Table1.Columns.Add("HouseNumber", Type.GetType("System.String"))
        Table1.Columns.Add("PostalCode", Type.GetType("System.String"))

        Dim Table2 As DataTable = New DataTable("Customers2")
        Table2.Columns.Add("Name", Type.GetType("System.String"))
        Table2.Columns.Add("Firstname", Type.GetType("System.String"))
        Table2.Columns.Add("State", Type.GetType("System.String"))

        Dim firstquery = From col In Table1.Columns Select col.columnName
        Dim notinsecondtable = From col In Table2.Columns Where Not firstquery.Contains(col.columnName)
    End Sub

Open in new window

Avatar of Sandiya


Sorry i have not used linq can u please explain me in detail how to proceed after the code
Avatar of pkbugudai
Flag of India image

Link to home
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
Avatar of Sandiya


Thanks all