Hopefully a quick question to be answered by the XML experts. I have a the following table with a XML type column with the below XML schema and data in one record:
INSERT INTO XMLTEST (testXML)
values ('<R>
<P N="Status" V="
Draft
" />
<P N="Approved For Publishing" V="
T
" />
<P N="Concealed From Publishing" V="
F
" />
<P N="Management System" V="
OMS
BMS
" />
</R>')
I need to conditionally replace the 'Approved For Publishing' value to F, and I thought the best was was to check against the N value name of the xml row first before changing the V value. I have been trying to get the below SQL to work but no luck. Can someone help point out what is wrong?
DECLARE @myDoc xml
SET @myDoc = (SELECT TOP 1 CAST(testXML AS VARCHAR(MAX)) FROM XMLTEST)
Select @myDoc
SET @myDoc.modify('
replace value of (/R/P/@V)[1]
with (
if (/R/P/N = ''Approved For Publishing'') then
"F"
else
"T"
)
')
SELECT @myDoc
New answer
The xml special characters

and
are nothing more than a new line (a Line Feed (LF) and a carriage return (CR)). I do not think, that this should really live within the XML's value. Line feeds should rather be added in your presentation layer.The following code shows the way how to update a tabel without the need of a variable or any cast.
One of the XMLs will look like this after the action:
The new line between
OMSandBMSremains in this approach.Previous answer
Some remarks / questions first?
VARCHAR(MAX)and then toXML(implicitly)?.modify()...NVARCHARif you deal with XML!@myDoc?You can try it with a
FLWOR XQuery:The result