I need a SQL script that will to pull an XML string from the DB [varchar(max)], inspect it, and update it if it fits a specific situation.
Imagine that my xml is in the following format:
<root>
<level1>
<level2>
<level3 />
<level3 />
</level2>
</level1>
<level1>
<level2>
<level3>
<level4>
<level5>
<level6 here="now is the time for XYZ">
<options>
<option this="that" />
<option me="you" />
</options>
</level6>
</level5>
</level4>
</level3>
</level2>
</level1>
<level1>
<level2>
<level3>
<level4>
<level5>
<level6 here="this one is not of interest">
<options>
<option this="that" />
<option me="you" />
</options>
</level6>
</level5>
</level4>
</level3>
</level2>
</level1>
<level1>
<level2>
<level3>
<level4>
<level5>
<level6 here="now is the time for ABC">
<options>
<option this="that" />
<option me="you" />
<option here="now" />
</options>
</level6>
</level5>
</level4>
</level3>
</level2>
</level1>
</root>
So, what I want to do is to update all elements whose name is "level6" and which have an attribute called "here" whose value begins with "now is the time". So, that should match just two elements above.
But, that's not the only selection criteria. The list of options must not contain <option here="now" />. So, that should leave us with just one element to update.
<level6 here="now is the time for XYZ">
<options>
<option this="that" />
<option me="you" />
</options>
</level6>
To that element, I then want to add the missing <option here="now" />, so that becomes:
<level6 here="now is the time for XYZ">
<options>
<option this="that" />
<option me="you" />
<option here="now" />
</options>
</level6>
So, the end result should be:
<root>
<level1>
<level2>
<level3 />
<level3 />
</level2>
</level1>
<level1>
<level2>
<level3>
<level4>
<level5>
<level6 here="now is the time for XYZ">
<options>
<option this="that" />
<option me="you" />
<option here="now" /> // <- this one new
</options>
</level6>
</level5>
</level4>
</level3>
</level2>
</level1>
<level1>
<level2>
<level3>
<level4>
<level5>
<level6 here="this one is not of interest">
<options>
<option this="that" />
<option me="you" />
</options>
</level6>
</level5>
</level4>
</level3>
</level2>
</level1>
<level1>
<level2>
<level3>
<level4>
<level5>
<level6 here="now is the time for ABC">
<options>
<option this="that" />
<option me="you" />
<option here="now" />
</options>
</level6>
</level5>
</level4>
</level3>
</level2>
</level1>
</root>
Assume that I can read the data out of the DB into a string, and that I know how to update the DB, so it's really how to manipulate the xml string in SQL (SQL Server).