检查重复项并从DataTable中删除数据库表的好方法?

时间:2013-08-15 09:41:50

标签: c# sql-server-ce-4

我的代码中有一个填充的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中存在于实际数据库表中的所有项目。

对于这个问题,什么是一个性能良好,经济有效的解决方案?

1 个答案:

答案 0 :(得分:1)

所以你需要为数据表和现有表格做好准备吗?我不确定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();
}