简体   繁体   中英

How to update database with new & modified records?

I've created a database (reading & filling data from a XML ) . I've done this with 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......

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 ?

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> . Then pass the unique ids of the xml - now serialized record - via a C# Stored Procedure call. You can loop though the collection and match each id using the stored procedure. This might be a performance hit if the records from the xml aren't too many.

In the stored procedure do a IF SELECT Count(*)... > 0 . If it returns value greater than 0 then the record exists:

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.

Let the stored procedure return a value or boolen to indicate the database was updated successfully.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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