我有一个xml
declare @EventBodyXml xml
set @EventBodyXml ='
<LocationCopied xmlns="http://schemas.datacontract.org/2004/07/someName" xmlns:i="http://www.w3.org/2001/XMLSchema-instance">
<Location xmlns:a="http://schemas.datacontract.org/2004/07/someAnotherName">
<a:Name>SomeLocationName</a:Name></Location>
</LocationCopied>'
我正在使用以下查询检索@uName变量中的位置名称
declare @uName nvarchar(100)
set @uName=@EventBodyXml.query(
'declare default element namespace "http://schemas.datacontract.org/2004/07/someName";
declare namespace a="http://schemas.datacontract.org/2004/07/someAnotherName";
/LocationCopied/Location/a:Name').value('.', 'nvarchar(100)') ;
然后用@uName进行一些操作,现在想用新的@uName值更新@EventBodyXml。
@uName='SomeNewUpdatedValue'
我尝试过以下这样的事情
set @EventBodyXml.modify('replace value of (
declare default element namespace "http://schemas.datacontract.org/2004/07/SCS.Domain.BusinessObjectManagement.Contract.EventModel";
declare namespace a="http://schemas.datacontract.org/2004/07/SCS.Domain.BusinessObjectManagement.Contract.ViewModel";
/LocationCopied/Location/a:Name/text() ) with sql:variable("@uName") ') ;
但是我收到了像
这样的错误Msg 2205,Level 16,State 1,Line 27 XQuery [modify()]:&#34;)&#34;是 预期
答案 0 :(得分:1)
你只是错过REPLACE
declare @EventBodyXml xml
set @EventBodyXml ='
<LocationCopied xmlns="http://schemas.datacontract.org/2004/07/someName" xmlns:i="http://www.w3.org/2001/XMLSchema-instance">
<Location xmlns:a="http://schemas.datacontract.org/2004/07/someAnotherName">
<a:Name>SomeLocationName</a:Name></Location>
</LocationCopied>'
declare @uName nvarchar(100)
set @uName=@EventBodyXml.query(
'declare default element namespace "http://schemas.datacontract.org/2004/07/someName";
declare namespace a="http://schemas.datacontract.org/2004/07/someAnotherName";
/LocationCopied/Location/a:Name').value('.', 'nvarchar(100)') ;
select @uName
set @EventBodyXml.modify('
declare default element namespace "http://schemas.datacontract.org/2004/07/someName";
declare namespace a="http://schemas.datacontract.org/2004/07/someAnotherName";
replace value of (/LocationCopied/Location/a:Name/text())[1]
with sql:variable("@uName")
');
print cast(@EventBodyXml as nvarchar(max))
我在这个问题中发现了一件有趣的事情,您必须在default namespace
变量中定义XML
declare @EventBodyXml xml
set @EventBodyXml ='
<LocationCopied xmlns="http://schemas.datacontract.org/2004/07/someName" xmlns:i="http://www.w3.org/2001/XMLSchema-instance">
<Location xmlns:a="http://schemas.datacontract.org/2004/07/someAnotherName">
<a:Name>XXXXXXXXXXXX</a:Name></Location>
</LocationCopied>'
declare @uName nvarchar(100)
set @uName='yyyyyyyyyyyyy'
set @EventBodyXml.modify('
declare default element namespace "http://schemas.datacontract.org/2004/07/someName";
declare namespace a="http://schemas.datacontract.org/2004/07/someAnotherName";
replace value of (/LocationCopied/Location/a:Name/text())[1]
with sql:variable("@uName")
');
print cast(@EventBodyXml as nvarchar(max))