【问题标题】:Update XML node using XQuery使用 XQuery 更新 XML 节点
【发布时间】:2017-01-16 10:44:41
【问题描述】:

我有一个 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 的节点的 Text

我试过这种方法

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 的 Text 元素?

【问题讨论】:

    标签: sql-server xml xquery


    【解决方案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
    

    【讨论】:

    • @NoorAShuvo,只是一个提示:您也可以通过变量引入要替换的文本。如果值取自结果集的列,请使用sql:column("ColumnName")
    猜你喜欢
    • 1970-01-01
    • 2011-05-29
    • 1970-01-01
    • 1970-01-01
    • 2023-03-09
    • 1970-01-01
    • 2011-06-12
    • 1970-01-01
    • 2022-10-04
    相关资源
    最近更新 更多