Note that there are some explanatory texts on larger screens.

plurals
  1. POInsert and Updating Multiple XML records to SQL 2008 - A solution, but maybe not the correct one?
    primarykey
    data
    text
    <p>Ok, so I have the following two test/example queries to INSERT and UPDATE data from XML into a SQL 2008 table. Fairly basic stuff in the fact the incoming XML structure will be matched to that of the SQL table (well the update of course has the necessary fields only - again just an example).</p> <p>INSERT STATEMENT</p> <pre><code>declare @passedXML xml set @passedXML='&lt;root&gt;&lt;record&gt;&lt;name&gt;Sam&lt;/name&gt;&lt;age&gt;37&lt;/age&gt;&lt;comments /&gt;&lt;/record&gt;&lt;record&gt;&lt;name&gt;Dan&lt;/name&gt;&lt;age&gt;32&lt;/age&gt;&lt;comments /&gt;&lt;/record&gt;&lt;/root&gt;' insert into test (name, age, comments) select x.record.query('name').value('.', 'varchar(255)'), x.record.query('age').value('.', 'int'), x.record.query('comments').value('.','varchar(255)') from @passedXML.nodes('root/record') as x(record) </code></pre> <p>So, no problems there, the two XML "records" get inserted as we need to.. Now onto the UPDATE statement:</p> <p>UPDATE STATEMENT</p> <pre><code>declare @passedXML xml set @passedXML='&lt;root&gt;&lt;record&gt;&lt;id&gt;3&lt;/id&gt;&lt;comments&gt;This is a new comment&lt;/comments&gt;&lt;/record&gt;&lt;record&gt;&lt;id&gt;2&lt;/id&gt;&lt;comments&gt;Michael Michael&lt;/comments&gt;&lt;/record&gt;&lt;/root&gt;' update test set comments = (select x.record.query('comments').value('.','varchar(255)') from @passedXML.nodes('root/record') as x(record) where id = x.record.query('id').value('.','bigint')) </code></pre> <p>Ok, so the update works - two XML "records" have their comments field updated based on the passed </p> <p><em><strong>MY QUESTION IS</em></strong></p> <p>Of course given the sample UPDATE above, the where clause is from the XML and not the TEST table.. so when the UPDATE is executed, the query says 100 (if say that is how many records are in table TEST) records updated.. of course only the two (in this case) records have been updated, but SQL had to run through the whole table?? I guess is there a way to somehow have the where clause from the XML attached to the underlying TEST table if that makes sense? i.e. to limit TEST to only the items updated?</p>
    singulars
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload