SQL 服务器 XQuery - 修改封闭元素的文本
SQL Server XQuery - Modify the text of a closed element
我在 SQL Server 2005 中有一个 XML 列,其中包含以下简化的 XML。
+----------+------------------+
| RecordID | ValueXML |
+----------+------------------+
| 1 | <value>x</value> |
| | |
+----------+------------------+
如果我想将该值更改为 y
,我使用以下 SQL 语句。
update ValueTable
set ValueXML.modify('
replace value of (/value/text())[1]
with ("y")')
where RecordID = 1
效果很好。 x
变为 y
。如果 value
设置为空,就会出现问题。
update ValueTable
set ValueXML.modify('
replace value of (/value/text())[1]
with ("")')
where RecordID = 1
发生这种情况后,table 看起来像这样。
+----------+------------------+
| RecordID | ValueXML |
+----------+------------------+
| 1 | <value /> |
| | |
+----------+------------------+
现在,我无法再设置该值。替换值查询执行成功,但未进行任何更改。
如何为封闭的 XML 元素设置文本?是否可以 "unclose" 元素?
您不能插入这样的值,因为您正在尝试替换文本但没有要替换的文本,因此它会执行但不会起作用。
这似乎与您遇到的问题相同 here。
感谢@BoogaWooga 为我指明了正确的方向。我能够在两个语句中进行替换。
首先,我确保该元素已关闭。无论元素是否关闭,此语句都有效。
update ValueTable
set ValueXML.modify('
replace value of (/value/text())[1]
with ("")')
where RecordID = 1
现在我知道该元素已关闭,我使用 insert text
将值插入到已关闭的元素中。
update ValueTable
set ValueXML.modify('
insert text{"x"}
into (/value[1])')
where RecordID = 1
我在 SQL Server 2005 中有一个 XML 列,其中包含以下简化的 XML。
+----------+------------------+
| RecordID | ValueXML |
+----------+------------------+
| 1 | <value>x</value> |
| | |
+----------+------------------+
如果我想将该值更改为 y
,我使用以下 SQL 语句。
update ValueTable
set ValueXML.modify('
replace value of (/value/text())[1]
with ("y")')
where RecordID = 1
效果很好。 x
变为 y
。如果 value
设置为空,就会出现问题。
update ValueTable
set ValueXML.modify('
replace value of (/value/text())[1]
with ("")')
where RecordID = 1
发生这种情况后,table 看起来像这样。
+----------+------------------+
| RecordID | ValueXML |
+----------+------------------+
| 1 | <value /> |
| | |
+----------+------------------+
现在,我无法再设置该值。替换值查询执行成功,但未进行任何更改。
如何为封闭的 XML 元素设置文本?是否可以 "unclose" 元素?
您不能插入这样的值,因为您正在尝试替换文本但没有要替换的文本,因此它会执行但不会起作用。
这似乎与您遇到的问题相同 here。
感谢@BoogaWooga 为我指明了正确的方向。我能够在两个语句中进行替换。
首先,我确保该元素已关闭。无论元素是否关闭,此语句都有效。
update ValueTable
set ValueXML.modify('
replace value of (/value/text())[1]
with ("")')
where RecordID = 1
现在我知道该元素已关闭,我使用 insert text
将值插入到已关闭的元素中。
update ValueTable
set ValueXML.modify('
insert text{"x"}
into (/value[1])')
where RecordID = 1