AKD
AKD

Reputation: 3966

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.

Upvotes: 0

Views: 193

Answers (1)

Conrad Lotz
Conrad Lotz

Reputation: 8828

Try this:

Serialize the xml into an class object - you can add it as a collection of this class object i.e 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.

Upvotes: 1

Related Questions