[英]How can I update a database table with a .Net DataTable and ignore existing records?
I have a .Net DataTable that contains records, all of which are "added" records. 我有一个包含记录的.Net DataTable,所有记录都是“添加”记录。 The corresponding table in the database may contain millions of rows. 数据库中的相应表可能包含数百万行。 If I attempt to simply call the "Update" method on my SqlDataAdapter, any existing records cause an exception to be raised due to a violation of the primary key constraint. 如果我尝试简单地在SqlDataAdapter上调用“ Update”方法,则任何现有记录都会由于违反主键约束而引发异常。 I considered loading all of the physical table's records into a second DataTable instance, merging the two, and then calling the Update method on the second DataTable. 我考虑过将所有物理表的记录加载到第二个DataTable实例中,将两者合并,然后在第二个DataTable上调用Update方法。 This actually works exactly like I want. 这实际上就像我想要的那样工作。 However, my concern is that if there are 30 billion records in the physical table, loading all of that data into a DataTable in memory could be an issue. 但是,我担心的是,如果物理表中有300亿条记录,那么将所有这些数据加载到内存中的DataTable中可能是一个问题。
I considered selecting a sub-set of data from the physical table and proceeding as described above, but the construction of the sub-query has proved to be very involved and very tedious. 我考虑过从物理表中选择数据的子集并按如上所述进行操作,但是事实证明,子查询的构造非常复杂且繁琐。 You see, I am not working with a single known table. 您知道,我不使用单个已知表。 I am working with a DataSet that contains several hundred DataTables. 我正在使用包含数百个数据表的数据集。 Each of the DataTables maps to its own physical table. 每个数据表都映射到其自己的物理表。 The name and schema of the tables are not known at compile time. 表的名称和架构在编译时未知。 This has to all be done at run time. 这必须在运行时完成。
I have played with the SqlBulkCopy class but have the same issue - duplicate records raise an exception. 我玩过SqlBulkCopy类,但有相同的问题-重复记录引发异常。
I don't want to have to dynamically construct queries for each table at run time. 我不想在运行时为每个表动态构造查询。 If that is the only way, so be it, but I just can't help but think that there must be a simpler solution using what Ado.Net provides. 如果那是唯一的方法,那就好了,但是我不禁认为,必须使用Ado.Net提供的解决方案更简单。
you could create your insertcommand like this: 您可以这样创建insertcommand:
declare @pk int = 1
declare @txt nvarchar(100) = 'nothing'
insert into #temp (id, txt)
select distinct @pk, @txt
where not exists (select id from #temp x where x.id = @pk)
assuming that your table #temp (temporary table used for this example) is created like this (with primary key on id) 假设您的表#temp(此示例中使用的临时表)是这样创建的(主键位于id上)
create table #temp (id int not null, txt nvarchar(100))
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.