========插入操作=========
====插入单个属性=====
--为第一个book节点插入属性name值为"直接插入"
set @data.modify('insert (attribute name {"直接插入"})into (/bookstore/book)[1]')
/*output:
<book category="COOKING" name="直接插入">
<title lang="en">Everyday Italian</title>
<author>Giada De Laurentiis</author>
<year>2005</year>
<price>30.00</price>
</book>
*/
======插入多个属性=======
--为第一个book节点插入属性Id值为"多值插入",name值为"多值插入"
set @data.modify('insert (attribute Id {"多值插入"},attribute name {"多值插入"})
into (/bookstore/book)[1]')
/*output:
<book category="COOKING" Id="多值插入1" name="多值插入2">
<title lang="en">Everyday Italian</title>
<author>Giada De Laurentiis</author>
<year>2005</year>
<price>30.00</price>
</book>
*/
======利用变量插入=========
--为第一个book节点插入属性var值为"变量插入"
declare @var nvarchar(10)
set @var='变量插入';
set @data.modify('insert (attribute var {sql:variable("@var")})into
(/bookstore/book)[1]')
/*output:
<book category="COOKING" var="变量插入">
<title lang="en">Everyday Italian</title>
<author>Giada De Laurentiis</author>
<year>2005</year>
<price>30.00</price>
</book>
*/
========修改操作=========
======一般修改=======
--将category=" CHILDREN "的第一个book节点的category属性值改为"CHILD"
set @data.modify('replace value of (bookstore/book[@category="CHILDREN"]/@category)[1]
with "CHILD"')
/*output:
<book category="CHILD">
<title lang="jp">Harry Potter</title>
<author>J K. Rowling</author>
<year>2005</year>
<price>29.99</price>
</book>*/
=======根据条件修改========
--将category=" WEB"的第二个book节点的category属性值改为"条件替换1"
--(如果第四个book节点的author数量大于1),反之改为“条件替换2”
set @data.modify('replace value of (/bookstore/book[@category="WEB"]/@category)[2]with
(if(count(/bookstore/book[4]/author)>1) then "条件替换1" else "条件替换2")' )
/*output:
<book category="条件替换2">
<title lang="cn">Learning XML</title>
<author>Erik T. Ray</author>
<year>2003</year>
<price>39.95</price>
</book>*/
=======根据属性名称修改========
--根据属性名称“category”来更新属性值
DECLARE @attributename VARCHAR(20)
DECLARE @title VARCHAR(20)
SELECT @attributename = 'category'--需要定位的属性名称
SELECT @title = 'new category' --属性需要更新的新值
SET @data.modify('
replace value of
(/bookstore/book/@*[local-name()=sql:variable("@attributename")])[1]
with sql:variable("@title")')
/*output:
<book category="new category">
<title lang="en">Everyday Italian</title>
<author>Giada De Laurentiis</author>
<year>2005</year>
<price>30.00</price>
</book>
*/
转载于:https://blog.51cto.com/shenlan/807529