[英]Change XML attribute values in SQL Server XML column
I have a SQL Server database table like the following:- 我有一个如下的SQL Server数据库表:-
Id (int) Info(xml)
------------------------
1 <xml....
2 <xml ...
3 <xml ...
The XML in each record in the Info field is something like:- “信息”字段中每个记录中的XML类似于:
<CodesParameter xmlns="http://mynamespace.com/"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:xsd="http://www.w3.org/2001/XMLSchema">
<Data Code="A1" HasMoreData="true">
.
.
</Data>
</CodesParameter>
I would like to be able to change the value of the <Data Code="...">
within the XML and have tried the following query:- 我希望能够在XML中更改
<Data Code="...">
的值,并尝试了以下查询:-
UPDATE MyTable
SET Info.modify('replace value of (Data[1]/@Code)with ("B1")')
WHERE Id = 2
Go
The message backs says that the query has executed successfully, but the value does not change. 该消息返回说查询已成功执行,但该值未更改。
I have tried declaring the namespace:- 我试过声明名称空间:
UPDATE MyTable
SET Info.modify('declare namespace myns="http://mynamespace.com/";
replace value of (/myns:WebTableParameter[1]/myns:DataTable[1]/@Code)with ("B1")')
WHERE Id = 2
Go
But the same result - the message says the query has executed successfully, but nothing has changed. 但是结果相同-消息显示查询已成功执行,但没有任何改变。
Any help appreciated. 任何帮助表示赞赏。
You have several problems: 您有几个问题:
UPDATE
) UPDATE
) Try this statement: 尝试以下语句:
;WITH XMLNamespaces(DEFAULT 'http://mynamespace.com/')
UPDATE dbo.MyTable
SET Info.modify('replace value of (/CodesParameter/Data[1]/@Code)[1] with ("B1")')
WHERE Id = 1
Basically, you need to start at the root of the XML document - you've missed (or left out) the <CodesParameter>
node entirely. 基本上,您需要从XML文档的根开始-您完全错过了(或忽略了)
<CodesParameter>
节点。 Also: you need to select a single attribute - thus you need another [1]
after your parenthesis. 另外:您需要选择一个属性-因此,在括号后还需要另一个
[1]
。
With this statement, I was able to update the XML as desired. 通过此语句,我能够根据需要更新XML。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.