【问题标题】:Modifying values of XML nodes with XML DML in SQL queries在 SQL 查询中使用 XML DML 修改 XML 节点的值
【发布时间】:2014-06-02 16:37:57
【问题描述】:

我正在尝试在 SQL 查询中使用 XML DML 修改 XML 数据库字段中的节点值。

假设我的表字段有这样的 xml:-

<ContentTree>
<ContentObject>
      <Id>1</Id>
      <Order>999</Order>
</ContentObject>
<ContentObject >
  <Id>5</Id>
  <Order>999</Order>
</ContentObject>
<ContentObject >
  <Id>3</Id>
  <Order>999</Order>
</ContentObject>
</ContentTree>

有没有一种方法可以在 SQL 查询中使用 XML DML 根据 Id 值修改 Order 值,例如 类似的东西:-

If  /ContentTree/ContentObject/Id /text()[1] ="5" 

Then 

Replace value of  /ContentTree/ContentObject/Order/text()[1]
with ("2")

我的真实数据很长,不太容易计算ContentObjects的索引号,所以我不想通过它的ContentObject索引号来识别特定的Order节点。

非常感谢。

【问题讨论】:

  • 我建议您在表格中选择它,更新值并再次保存在 xml 中。我认为,它更简单。

标签: sql xml sql-server-2008 dml


【解决方案1】:

这是我的例子:

DECLARE  @table TABLE (value XML)

INSERT INTO @table
(
    [value]
)
VALUES
(
  N'<ContentTree>
<ContentObject>
      <Id>1</Id>
      <Order>999</Order>
</ContentObject>
<ContentObject>
  <Id>5</Id>
  <Order>999</Order>
</ContentObject>
<ContentObject >
  <Id>3</Id>
  <Order>999</Order>
</ContentObject>
</ContentTree>'
)

UPDATE @table
SET
    [value].modify('replace value of (/ContentTree/ContentObject/Id[text()="5"]/../Order/text())[1] with "5"')

SELECT *
FROM @table t

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-02-10
    • 1970-01-01
    • 2017-06-25
    • 2022-12-06
    • 1970-01-01
    相关资源
    最近更新 更多