这是一个工作示例。鉴于有效的 XML 具有严格的规则,我想不出字符串操作不起作用的原因。至少,作为字符串搜索关键的“<”不应该存在于 XML 标记名称之外。
-- create a sample table variable with a few variations
declare @T table (sample xml)
insert @T select '
<root>
<child1>blah</child1>
</root>'
insert @T select '
<root>
<child1>blah1</child1>
<child1>blah2</child1>
</root>'
insert @T select '
<root>
<child1>
blah1
<child2>blah2</child2>
</child1>
</root>'
insert @T select '
<root>
<child0>
<child1>
<child4>
<child3>blah2</child3>
</child4>
</child1>
</child0>
</root>'
-- peek at the content
select * from @T
-- perform the replacements as many times as required
-- note that the string "stackoverflow123" is expected to NEVER
-- exist in your data, or use another string if it does!
while @@rowcount > 0
begin
update T
set sample = stuff(X.A, Y.B, Z.C - Y.B + 9, '<child1Root>'+
replace(replace(
SUBSTRING(X.A, Y.B, Z.C - Y.B + 9),
'<child1>','<stackoverflow123>'),
'</child1>','</stackoverflow123>')
+'</child1Root>')
from @T T
cross apply (
select convert(varchar(max),sample)) X(A)
cross apply (
select patindex('%<child1>%</child1>%', X.A)) Y(B)
cross apply (
select charindex('</child1>', X.A, Y.B+1)) Z(C)
where Z.C > 0
end
-- finally revert the placeholder string back to "child1"
update @T
set sample = replace(convert(varchar(max),sample), 'stackoverflow123', 'child1')
-- inspect the finished product
select * from @T