在 T-SQL 中更新没有文本的 XML 字段 [英] Update XML field with no text in T-SQL
本文介绍了在 T-SQL 中更新没有文本的 XML 字段的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我在更新 SQL 字段时遇到了一个问题,因为我编写的内容对于存在文本的 xml 节点非常有效,但是当节点为空时它会跳闸.
I've come across a problem in updating an SQL field in that what I've written works perfectly for xml nodes with a text present, however it trips up when the node is empty.
<filemeta filetype="Video">
<heading>TEST</heading>
<description />
</filemeta>
这段代码工作正常;
UPDATE filemetaDB SET filemeta.modify('replace value of (/filemeta/heading/text())[1] with "TEST"');
然而这会中断;
UPDATE filemetaDB SET filemeta.modify('replace value of (/filemeta/description/text())[1] with "notworking!"');
感谢您的帮助.
推荐答案
这个节点 (/filemeta/description/text())[1]
在 XML 中不存在所以没有什么可代替.你必须做一个插入.如果您有一个混合空节点和带有值的节点的场景,您必须运行两个更新语句.
This node (/filemeta/description/text())[1]
does not exist in the XML so there is nothing to replace. You have to do an insert instead. If you have a scenario where you have a mix of empty nodes and nodes with a value you have to run two update statements.
declare @filemetaDB table(filemeta xml)
insert into @filemetaDB values
('<filemeta><description>Not empty</description></filemeta>'), -- Not empty node
('<filemeta><description/></filemeta>'), -- Empty node
('<filemeta></filemeta>') -- Missing node
-- Replace value for nodes with value
update @filemetaDB
set filemeta.modify('replace value of (/filemeta/description/text())[1] with "TEST 1"')
where filemeta.exist('/filemeta/description/text()') = 1
-- Add text node for empty nodes
update @filemetaDB
set filemeta.modify('insert text{"TEST 2"} into (/filemeta/description)[1]')
where filemeta.exist('/filemeta/description/text()') = 0
select *
from @filemetaDB
结果:
filemeta
------------------------------------------------------
<filemeta><description>TEST 1</description></filemeta>
<filemeta><description>TEST 2</description></filemeta>
<filemeta />
这篇关于在 T-SQL 中更新没有文本的 XML 字段的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文