简体   繁体   English

如何使用新记录和修改记录来更新数据库?

[英]How to update database with new & modified records?

I've created a database (reading & filling data from a XML ) . 我已经创建了一个database (从XML读取和填充数据)。 I've done this with SqlBulkCopy . 我已经使用SqlBulkCopy做到了这一点。 But the scenario is whenever the XML is updated(may be a new record inserted or a existing record modified) ...thus the database should also be updated , So I've created a solution that first all the records of all tables should be removed in database & again perform the SqlBulkCopy , so the data could be updated...... 但是场景是每当XML更新时(可能是插入新记录或修改现有记录) ...因此数据库也应更新 ,因此,我创建了一个解决方案,首先应该对所有表的所有记录进行更新 。在数据库中删除并再次执行SqlBulkCopy ,以便可以更新数据……

But it seems to very worst way. 但这似乎是最糟糕的方式。

Is there any way to update only those records, which needs to be as well as insert new record if source XML have any new record ? 有什么方法可以只更新那些记录,如果源XML有任何新记录,则需要更新这些记录并插入新记录?

I also tried some dataset merge operations, but I couldn't figured out the right way to use them. 我也尝试了一些数据集合并操作,但是我找不到正确的使用方法。

Try this: 尝试这个:

Serialize the xml into an class object - you can add it as a collection of this class object ie List<object> . 将xml序列化为类对象-您可以将其添加为该类对象的集合,即List<object> Then pass the unique ids of the xml - now serialized record - via a C# Stored Procedure call. 然后,通过C#存储过程调用传递xml的唯一ID(现已序列化记录)。 You can loop though the collection and match each id using the stored procedure. 您可以遍历集合并使用存储过程匹配每个id。 This might be a performance hit if the records from the xml aren't too many. 如果xml中的记录不是太多,这可能会降低性能。

In the stored procedure do a IF SELECT Count(*)... > 0 . 在存储过程中,执行IF SELECT Count(*)... > 0 If it returns value greater than 0 then the record exists: 如果返回的值大于0,则记录存在:

IF(SELECT COUNT(*) FROM table where uniqueid = @id) > 0)
BEGIN
    UPDATE table ... WHERE uniqueid = @id
END
ELSE
BEGIN
   INSERT INTO table (...) VALUES(...)
END 

Alternatively make use of MERGE INTO which is also great to use. 或者使用也很有用的MERGE INTO

Let the stored procedure return a value or boolen to indicate the database was updated successfully. 让存储过程返回一个值或布尔值以指示数据库已成功更新。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM