我需要比较两个dataTables dataTable A包含客户端计算机上的当前数据集 dataTable B包含对dataTable A的未来更新。
dataTable A structure
ID | firstname | lastName
1 | "test" | "last"
2 | "whatever" | "someone"
3 | "hi" | "hello
dataTable B Structure
ID | firstname | lastName
1 | "updated" | "yes"
2 ->deleted
3 | "hi" | hello" ->unchanged
4 | "new" |record " ->row added
当我去dataTableA.merge(datatableB)
时我基本上只是使用dataTableB添加了行来获取dataTableA 所以例如
ID | firstname | lastName
1 | "test" | "last"
2 | "whatever" | "someone"
3 | "hi" | "hello
1 | "updated" | "yes"
3 | "hi" | hello" ->unchanged
4 | "new" |record " ->row added
它与ID不匹配,无法更新或删除。我只是想比较两个表,更新表A看起来应该像表B.我不太确定如何正确地完成这个。
基本上客户端机器中有一个SQL表需要完成更新并与传入的数据表B完全同步。理论上我只想拿表B并基本上更新表A.所以在我之后需要更新SQL表。我试过这样的事情。
Dim adapter = New SqlDataAdapter("select * from test_table2", connection)
Using (New SqlCommandBuilder(adapter))
adapter.Fill(dTable)
connection.Open()
adapter.Update(dTable)
End Using
似乎不起作用。
答案 0 :(得分:0)
如果数据表最终应该相同,而不是使用
dataTableA.merge(datatableB)
尝试
dataTableA=datatableB.Copy
从这里得到这个信息 https://msdn.microsoft.com/en-us/library/system.data.datatable.copy(v=vs.110).aspx
答案 1 :(得分:0)
您的两个数据表是分开创建的,彼此独立。在此上下文中,您可以使用以下DataTable和LINQ操作,例如
Intersect
在两个DataTables中找到匹配的行,Except
仅在一个表中查找唯一行ImportRow
将一个DataTable的特定行复制到另一个。Copy
将整个数据表复制到另一个可能是这样的
Dim dtA As DataTable 'Your original Table A
Dim dtB As DataTable 'Your modified Table B
Dim dtC As DataTable 'Unchanged Rows
Dim dtD As DataTable 'Final synchronized Table
Dim dtE As DataTable 'Deleted Rows
'Populate your Table A and Table B into dtA and dtB
'get unchanged rows into dtC (all rows - changed - deleted)
dtC = dtA.AsEnumerable.Intersect(dtB.AsEnumerable, DataRowComparer.Default).CopyToDataTable
'Copy all unchanged rows to final table
dtD = dtC.Copy
'Copy the structure to blank datatable
dtE = dtC.Clone
'process modified rows (changed + deleted) i.e. (all rows - unchanged rows)
For Each cdRow As DataRow In dtA.AsEnumerable.Except(dtC.AsEnumerable, DataRowComparer.Default).CopyToDataTable.Rows
'check if this row exists in modified rows
If dtB.Select("cid = " & cdRow.Item("cid").ToString).Count > 0 Then
'This is a modified row copy it to the final table or process it to database
dtD.ImportRow(dtB.Select("cid = " & cdRow.Item("cid").ToString).CopyToDataTable.Rows(0))
Else
'This is a deleted row copy it to the deleted records table or process it directly to the database
dtE.ImportRow(cdRow)
End If
Next
'Now dtE contains your deleted rows
'Finally dtD is your synchronized datatable
假设和其他细节: