比较两个相似但不相同的数据表 [英] Compare two similar but not identical data tables

查看:167
本文介绍了比较两个相似但不相同的数据表的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有两个数据表,它们有一个共同的主键列,但是不同的结构,因为它们是从不同的表创建的。我想检查数据表B中与A相比缺少哪些行,目的是将缺少的行添加到数据库中。



请查看这一个,它们提供了很好的答案,但是通常假定数据表是相同的。



由于我想获取插入的新行列表,有没有办法,我可以这样做而不迭代行和检查PK?如果我没有错,合并将保留旧行,我不想重新提交到数据库。



这两个表只有几十行,最多几百个。

编辑:这两个源表位于不同的数据库/服务器上,所以我不能轻易做SQL中的
比较。我更喜欢消费的应用程序,无论如何,我可以在完成之前添加一些更多的行处理。

解决方案

我希望我已经理解你的需求正确,但如何使用Linq?将2个表的键加载到2 IEnumerable< keytype> 对象中,例如(假设您的键是 int

  IEnumerable< int& keys1,keys2; 
//将键加载到这些集合中的代码
//查找keys2中keys2中缺少的keys2中的键:
var missingKeys = keys1.Where(k1 =>!keys2。任何(k2 => k2 == k1));

HTH


I have two data tables which have a primary key column in common but otherwise different structures as they're created from different tables. I'd like to check which rows are missing from data table B compared to A, with the aim of adding in the missing rows to the database.

I've had a look at questions like this one, which provide good answers but the data tables are usually assumed to be the same.

Since I want to get a list of new rows for inserting, is there any way I can do this without iterating through the rows and checking the PKs? If I'm not mistaken, Merge will keep the old rows, which I don't want to resubmit to the database.

Both tables will have only a few dozen rows, a couple of hundred maximum. Would the computational hit of doing it row-by-row be negligible anyway?

edit: the two source tables are on different databases/servers, so I can't easily do the comparison in SQL. I'd prefer the consuming application to do it anyway, as I may add some more row processing before I'm done.

解决方案

I hope I've understood your needs correctly, but how about using Linq? Load the keys of your 2 tables into 2 IEnumerable<keytype> objects, e.g. (assuming your keys are of type int)

IEnumerable<int> keys1, keys2;
// code to load the keys into these collections
// to find the keys in keys1 that are missing from keys2:
var missingKeys = keys1.Where(k1 => !keys2.Any(k2 => k2 == k1)); 

HTH

这篇关于比较两个相似但不相同的数据表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆