使用XQuery更新XML节点

时间:2017-01-16 10:44:41

标签: sql-server xml xquery

我有一个XML类型变量@XMLData。

DECLARE @xmlData XML 
DECLARE @tempXML XML 

SET @xmlData =N'<ArrayOfResult>
<Result>
  <ID>1</ID>
  <Text>This text should be updated to new text</Text>
</Result>
<Result>
  <ID>2</ID>
  <Text>This text is okay</Text>
</Result>
</ArrayOfResult>';

我想更新 ID 为1的节点的文字

我试过这种方式

SET @tempXML = @xmlData
SELECT @xmlData;

SET @tempXML.modify('replace value of (/ArrayOfResult/Result/Text/text())[1]     with ("This text is okay")');

SELECT @tempXML

但是在这里,我必须提到节点索引[1]来更新第一个节点。 如何更新 ID = 1的文本元素?

1 个答案:

答案 0 :(得分:1)

试试这样:

DECLARE @xmlData XML 
DECLARE @tempXML XML 

SET @xmlData =N'<ArrayOfResult>
<Result>
  <ID>1</ID>
  <Text>This text should be updated to new text</Text>
</Result>
<Result>
  <ID>2</ID>
  <Text>This text is okay</Text>
</Result>
</ArrayOfResult>';

SET @tempXML = @xmlData
SELECT @xmlData;

- 您可以使用变量传入ID

DECLARE @id INT=1;

SET @tempXML.modify('replace value of (/ArrayOfResult/Result[ID=sql:variable("@id")]/Text/text())[1]     with ("This text is okay")');

SELECT @tempXML