根据数据库表检查重复项并将其从DataTable中删除的好方法
本文关键字:DataTable 删除 方法 数据库 检查 | 更新日期: 2023-09-27 18:27:41
我的代码中有一个填充的DataTable:
我使用的是SQL Server CE 4.0,为了解决性能问题,我使用了SqlCeBulkCopy
:
SqlCeBulkCopyOptions options = new SqlCeBulkCopyOptions();
options = options |= SqlCeBulkCopyOptions.KeepNulls;
// Check for DB duplicates
using (SqlCeBulkCopy bc = new SqlCeBulkCopy(strConn, options))
{
dt = RemoveDuplicateRows(dt, "Email");
bc.DestinationTableName = "Recipients";
bc.WriteToServer(dt);
}
RemoveDuplicateRows
将从DataTable中删除重复项,但不会对数据库中已存在的内容进行检查。
在将数据表传递给WriteToServer(dt)
之前,我希望有效地删除实际数据库表中存在的DataTable中的所有项。
对于这个问题,什么是性能好、经济高效的解决方案?
所以您需要对数据表和现有表进行marge处理,对吗?我不确定sql-ce是否支持临时表,我用ms-sql做了一些模拟程序,这里是伪代码
string tmpTableDefinition = "create table #tmpEmails (...)";
using(var connection = new SqlCeConnection(connectionString))
{
//Create temp table
var tmpTableCommand = new SqlCeCommand(tmpTableDefiniton, connection);
tmpTableCommand.ExecuteNonQuery();
//Bulk copy to the temp table, note that bulk copy run faster if the teble is empty
//which is always true in this case...
using (var bc = new SqlCeBulkCopy(connection, options))
{
bc.DestinationTableName = "#tmpEmails";
bc.WriteToServer(dt);
}
//Run a sp, that have temp table and original one, and marge as you wish in sql
//for sp to compile properly, you would have to copy tmp table to script too
var spCommand = new SqlCommand("sp_MargeTempEmailsWithOriginal", connection);
spCommand.Type = SP //Don't remember exact prop name and enum value
spCommand.ExecuteNonQuery();
}