如何使用TSql更新xml中的特定元素值?

时间:2016-05-24 14:45:43

标签: sql tsql

我的脚本只能找到第一个匹配并更新它但我想更新匹配id的记录。这是我的示例xml: -

    create table catalog
(
catalog xml
);
Insert into catalog
select '<catalog>
   <book> 
      <id>1</id>
      <read>true</read>
   </book>
   <book> 
      <id>2</id>
      <read>true</read>
   </book>
   <book> 
      <id>3</id>
      <read>true</read>
   </book>
   <book> 
      <id>4</id>
      <read>true</read>
   </book>
   </catalog>'

我使用此脚本修改一个元素的值: -

UPDATE catalog
SET catalog.modify('replace value of (/catalog/book/read/text())[1] with "false"')
WHERE catalog.value('(/catalog/book/id/text())[1]','int') = 3

当我使用id = 1但无法更新Id 2,3或4时,此脚本会更新记录。

1 个答案:

答案 0 :(得分:0)

如果您有一些识别单个书籍节点的元素,我认为我们可以使用替换。

--Replace could work if your id were and element of book
/*
  <book id="3">   
    <read>true</read>
  </book>*/

--This query only work for the XML above 
UPDATE catalog_tbl
SET [catalog].modify('replace value of 
(/catalog/book/id[@id=("3")]/read/text())[1] with ("false")')
go

相反,如果删除和插入是可接受的更新方法,则下面的脚本将起作用。

--delete your node first
UPDATE catalog_tbl
SET [catalog].modify('delete (/catalog/book)[3]')

--then insert the element back with read=false
UPDATE catalog_tbl
SET [catalog].modify('insert <book><id>3</id><read>false</read></book> into (/catalog)[1]')
go