I have the following problem and hope someone could help.
I have a SQL Server database with a couple thousand rows. Every row consist of a column with an ID and a column with XML data.
This XML data looks something like:
<record id="1">
<field tag="aa" occ="1" lang="nl-NL" invariant="false">Jan</field>
<field tag="aa" occ="1" lang="en-US" invariant="false">John</field>
<field tag="aa" occ="1" lang="de-DE" invariant="false">der Jan</field>
<field tag="aa" occ="2" lang="nl-NL" invariant="false">Jan2</field>
<field tag="aa" occ="2" lang="en-US" invariant="false">John2</field>
<field tag="ab" occ="1">Something</field>
<field tag="ac" occ="1" lang="de-DE" invariant="false">Rechnung</field>
<field tag="ac" occ="1" lang="nl-NL" invariant="false">rekening</field>
<field tag="ad" occ="1">Something2</field>
<field tag="ae" occ="1" lang="nl-NL" invariant="false">stoeptegel</field>
</record>
I would like to edit this XML for every record according to the following rules:
- For every unique occ (occurence), tag combination only 1 @invariant attribute can be true
- If a has @lang=en-US attribute, then @invariant has to be 'true'. Remaining fields with same occ, tag combination have to remain 'false'. (like tag aa in sample code)
- If a has @lang=nl-NL attribute, but no @lang=en-US, then @invariant has to be 'true' for 'nl-NL'. Remaining fields with same occ, tag combination have to remain 'false'. (like tag ac in sample code)
- If a occ, tag combination has only 1 instance, then @invariant has to be 'true'. So independent of @lang value. (like tag ae in sample code)
After running 1 or more SQL queries, the code should look like:
<record id="1">
<field tag="aa" occ="1" lang="nl-NL" invariant="false">Jan</field>
<field tag="aa" occ="1" lang="en-US" invariant="true">John</field>
<field tag="aa" occ="1" lang="de-DE" invariant="false">der Jan</field>
<field tag="aa" occ="2" lang="nl-NL" invariant="false">Jan2</field>
<field tag="aa" occ="2" lang="en-US" invariant="true">John2</field>
<field tag="ab" occ="1">Something</field>
<field tag="ac" occ="1" lang="de-DE" invariant="false">Rechnung</field>
<field tag="ac" occ="1" lang="nl-NL" invariant="true">rekening</field>
<field tag="ad" occ="1">Something2</field>
<field tag="ae" occ="1" lang="nl-NL" invariant="true">stoeptegel</field>
</record>
My problem is creating the correct SQL query, to replace all nodes for all records, according to the above rules.
So far I came up with this:
while exists
(
select *
from databasetable
where xmlcolumn.exist('/record/field/@invariant[.="false"]') = 1
)
update databasetable
set xmlcolumn.modify
('replace value of (/record/field/@invariant[.="false"])[1] with "true"')
Which edits every value of @invariant into 'true'.
Could someone help me build the correct query? Thanks in advance!