2

I have a MSSQL table like such:

id     | name
-----------------------------
1        Gerald
2        Ron
3        Becky

And an XML document:

<People>
    <Person>
        <Name>Gerald</Name>
    </Person>
    <Person>
        <Name>Ron</Name>
    </Person>
    <Person>
        <Name>Becky</Name>
    </Person>
</People>

The primary key is ID, the XML document doesn't care about ID's, and Name's are unique.

The XML document changes, and my application should add new rows to the table for any <Person> not found in the SQL table.

Sure I can loop through the entire SQL table for each <Person> checking for a row and adding the row if it's not found, but is there a better way?

To add additional complexity, If I update a <Person>'s name in the XML file, it needs to update the same row that person was at before in the SQL table.

2
  • What language is this to be done in? c# or sql? Commented May 24, 2013 at 17:15
  • The client application that reads the XML file is in C#, and I'm using MSSQL to store the data. Commented May 24, 2013 at 17:16

2 Answers 2

2

Try this

declare @data xml = '<People>
    <Person>
        <Name>Gerald</Name>
    </Person>
    <Person>
        <Name>Ron</Name>
    </Person>
    <Person>
        <Name>Becky</Name>
    </Person>
</People>'

--Convert xml to rows example:
SELECT N.value('.', 'varchar(50)') as value 
FROM @data.nodes('/People/Person/Name') as T(N)

-- use merge to find rows and insert when not found
Merge Table1 as tgt
using (
        SELECT N.value('.', 'varchar(50)') as Name 
        FROM @data.nodes('/People/Person/Name') as T(N)
      ) src
on (tgt.name = src.name)
when not matched then
insert (name)
values (src.name);

To update row, you need some kind of id in file to identify row to update

Sign up to request clarification or add additional context in comments.

Comments

1

You could add an attribute to <Person>, which indicated that it was already in the database:

<People>
    <Person inserted="1">
        <Name>Gerald</Name>
    </Person>
    <Person inserted="1">
        <Name>Ron</Name>
    </Person>
    <Person inserted="0">
        <Name>Becky</Name>
   </Person>
</People>

1 Comment

So if it's a fresh XML document, load the SQL database with the XML elements, then write a new XML document containing the inserted ID's. On an updated XML document, if one of the people changes, add changed="Yes" and import only those, using the inserted ID's, and write a new XML document without the changed attribute. Would that work?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.