3

Table Name : TBL_CLIENTS Table Field : XMLDATA

<REPORT xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" DESCRIPTION="TestClient" FILENUM="1234">
  <!--<REPORT DESCRIPTION="TestClient" FILENUM="1234">-->
  <TRACKING>
    <FIRSTNAME>Bobby</FIRSTNAME>
    <LASTNAME>Butcher</LASTNAME>
  </TRACKING>
</REPORT>

I want to change both the FIRSTNAME and LASTNAME. Is there anyway I can do it in a single query? The only way I can figure it out is using two queries.

UPDATE TBL_CLIENTS
SET [XMLDATA].modify('replace value of (/REPORT/TRACKING/FIRSTNAME/text())  [1] with ("Franny")')
WHERE ORDERID = 5

and

UPDATE TBL_CLIENTS
SET [XMLDATA].modify('replace value of (/REPORT/TRACKING/LASTNAME/text())[1]  with ("Farmer")')
WHERE ORDERID = 5

1 Answer 1

3

It's not possible - per MSDN, replace has to work on a single instance of an XML node - but you could avoid doing two UPDATEs on the table this way:

DECLARE @doc xml = '<REPORT xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" DESCRIPTION="TestClient" FILENUM="1234">
  <!--<REPORT DESCRIPTION="TestClient" FILENUM="1234">-->
  <TRACKING>
    <FIRSTNAME>Bobby</FIRSTNAME>
    <LASTNAME>Butcher</LASTNAME>
  </TRACKING>
</REPORT>';

DECLARE @t table (xmldata xml);

insert @t (xmldata) values (@doc);

-- grab the XML data from the table for manipulation...
DECLARE @xmlData xml;
SELECT @xmlData = xmldata FROM @t;

set @xmlData.modify('replace value of (/REPORT/TRACKING/FIRSTNAME/text())  [1] with ("Franny")')                   
set @xmlData.modify('replace value of (/REPORT/TRACKING/LASTNAME/text())   [1] with ("Farmer")')

-- now we only need to do one update on the table itself.
UPDATE @t 
SET [XMLDATA] = @xmlData

SELECT * FROM @t;

I know this isn't exactly what you were asking for, but it should result in less locking time and better performance on the table - if that's something you're aiming for.

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

Comments

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.