[英]Replace value of empty XML node in SQL Server's XQuery
我尝试了以下方法,但没有找到一种方法来删除空节点值而不删除它并且不使用XML属性。
替换节点在MS-SQL中不可用。
DECLARE @doc xml
SET @doc = '
<f1>1</f1>
<f2/>
'
print '1) ' + convert(varchar(4000),@doc)
SET @doc.modify('
replace value of (/f1/text())[1]
with (''v2'')
')
print '2) ' + convert(varchar(4000),@doc)
SET @doc.modify('
replace value of (/f1/text())[1]
with (''v3'')
')
print '3) ' + convert(varchar(4000),@doc)
SET @doc.modify('
replace value of (/f2/text())[1]
with (''v4'')
')
print '4) ' + convert(varchar(4000),@doc) + ' did not replace f2 value'
begin try
exec sp_executesql N'
SET @doc.modify(''
replace value of (/f2)[1] with (''''v5'''')
'')
print ''5) '' + convert(varchar(4000),@doc)
',N'@doc xml',@doc
end try begin catch
print '5) ' + error_message()
end catch
begin try
exec sp_executesql N'
SET @doc.modify(''
replace value of (/f2/node())[1]
with (''''v6'''')
'')
print ''6) '' + convert(varchar(4000),@doc)
',N'@doc xml',@doc
end try begin catch
print '6) ' + error_message()
end catch
begin try
exec sp_executesql N'
SET @doc.modify(''
replace value of (/f2)[1]
with (''''<f2>v7/f2>'''')
'')
print ''7) '' + convert(varchar(4000),@doc)
',N'@doc xml',@doc
end try begin catch
print '7) ' + error_message()
end catch
SET @doc.modify('
delete (/f2)
')
SET @doc.modify('
insert <f2>v8</f2> as last
into (.)[1]
')
print '8) ' + convert(varchar(4000),@doc) + ' only delete and add works'
/*
output:
1) <f1>1</f1><f2/>
2) <f1>v2</f1><f2/>
3) <f1>v3</f1><f2/>
4) <f1>v3</f1><f2/> did not replace f2 value
5) XQuery [modify()]: The target of 'replace value of' must be a non-metadata attribute or an element with simple typed content, found 'element(f2,xdt:untyped) ?'
6) XQuery [modify()]: The target of 'replace value of' cannot be a union type, found '(element(*,xdt:untyped) | comment | processing-instruction | text) ?'.
7) XQuery [modify()]: The target of 'replace value of' must be a non-metadata attribute or an element with simple typed content, found 'element(f2,xdt:untyped) ?'
8) <f1>v3</f1><f2>v8</f2> only delete and add works
*/
好吧,我认为像这样的事情会做到的
DECLARE @doc xml
SET @doc = '
<f1>1</f1>
<f2/>
'
print '1) ' + convert(varchar(4000),@doc)
SET @doc.modify('
insert text{"v9"} into (/f2)[1]
')
print '2) ' + convert(varchar(4000),@doc)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.