SQL大容量数据插入或更新



好的,开始吧。我面临的要求是,我在数据库中有一个表,比如"MyDbTable",里面有很多数据

假设它有三列,如:

ColA ColB ColC

1 nbsp nbsp nbsp nbsp nbsp;a nbsp nbsp nbsp ab
2 nbsp nbsp nbsp nbsp nbsp;b nbsp nbsp nbsp bc
3 nbsp nbsp nbsp nbsp nbsp;c nbsp nbsp nbsp cd


ColA是身份

现在我调用一个Web服务,预期结果由大约1500行组成。

模式与返回的结果相同,比如:

ColA ColB ColC

1 nbsp nbsp nbsp nbsp nbsp;a nbsp nbsp nbsp xy
3 nbsp nbsp nbsp nbsp nbsp;c nbsp nbsp nbsp yz
4 nbsp nbsp nbsp nbsp nbsp c nbsp nbsp nbsp yz

现在我真正想做的是检查我在服务结果中的现有记录,并在MyDbTable中更新它们,在这种情况下,它将是ColA中有1和3的记录。我必须更新它们。对于webservice中ColA值为4的记录,结果是新的,所以我必须插入它。

现在的问题是MyDbTable有数千行,而服务也返回了许多行。

我知道最简单的方法是暴力,我们迭代每个记录,检查它,然后通过应用程序或存储过程进行处理。

我真正想知道的是如何以最优化的方式做到这一点。

这是我认为是最有效的方法(不过还没有衡量):

  1. 使用SqlBulkCopy Class提供的批量复制操作,将web服务返回的整个表复制到数据库的临时表中。

  2. 使用单个SQL ServerMERGE语句将临时表中的"更新或插入"操作放入实际表中。

如果使用的SQL Server版本早于2008,则可以使用带有OUTPUT子句的UPDATE语句,而不是MERGE

你可以做一件事。。。

从web服务中获取第一行,并获取其ID Say"1",然后将其传递给GetRecordFromDB方法。。。

现在,如果该方法返回某个对象,则从您从Web服务中找到的值中设置其值。。然后调用一个方法来更新数据库中的记录。

所以代码逻辑是

object updateorinsert = library.getobjectbyid(IDFROMFirstRecordOfWebservice)
if (updateorinsert  != null)
{
updateorinsert.ColAValue = WebserviceData.ColAValue
}
updateorinsert.ColBValue = WebserviceData.ColBValue
updateorinsert.ColCValue = WebserviceData.ColCValue
library.UpdateRecordOrInsertInDB(updateorinsert);

您也可以使用SqlBulkCopy,使用临时表可以执行适合您所有需要的插入/更新。

您可以在BulkInsert之后删除暂存表和实际表中的所有ID,然后将所有记录从暂存复制到实际。

使用SQLBulkCopy插入/更新数据库

我希望上面的链接能有所帮助。

最新更新