表名:TBL_CLIENTS 表字段: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>
我想要更改FIRSTNAME和LASTNAME。无论如何我可以在一个查询中执行此操作吗?我能弄清楚的唯一方法是使用两个查询。
UPDATE TBL_CLIENTS
SET [XMLDATA].modify('replace value of (/REPORT/TRACKING/FIRSTNAME/text()) [1] with ("Franny")')
WHERE ORDERID = 5
和
UPDATE TBL_CLIENTS
SET [XMLDATA].modify('replace value of (/REPORT/TRACKING/LASTNAME/text())[1] with ("Farmer")')
WHERE ORDERID = 5
答案 0 :(得分:1)
这是不可能的 - 每MSDN,替换必须在XML节点的单个实例上工作 - 但是你可以避免以这种方式在表上执行两个UPDATE
:
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;
我知道这并不是你所要求的,但它会导致更少的锁定时间和更好的表现 - 如果这是你的目标。