问题描述
declare @idx int = 1
while (@idx <= @NumThresholds)
begin
declare @strIdx nvarchar(100) = convert(varchar(100),@idx)
declare @xqueryString nvarchar(max) = concat('replace value of (//*:ElecTariffElements/*:ThresholdMatrix/*:Thresholds/*:BlockThreshold/text())[',@strIdx,'] with "0"')
set @xml.modify(@xqueryString)
set @idx = @idx + 1
end
我要在其中更新BlockThreshold
元素的每个值。
但是我得到了错误:
我也尝试过像这样使用sql:variable("@strIdx")
:
declare @idx int = 1
while (@idx <= @NumThresholds)
begin
declare @strIdx nvarchar(100) = convert(varchar(100),@idx)
set @xml.modify('replace value of (//*:ElecTariffElements/*:ThresholdMatrix/*:Thresholds/*:BlockThreshold/text())[sql:variable("@strIdx")] with "0"')
set @idx = @idx + 1
end
但这会导致我收到此错误:
XQuery [modify()]:仅“ http://www.w3.org/2001/XMLSchema#decimal?”, 'http://www.w3.org/2001/XMLSchema#boolean?'或'node()*'表达式作为谓词,可以找到'xs:string?'
我只想遍历元素并替换值,但似乎比我预期的要困难得多。
非常感谢您的帮助!
解决方法
declare @xml xml = N'
<ElecTariffElements>
<ThresholdMatrix>
<Thresholds>
<BlockThreshold>1</BlockThreshold>
<BlockThreshold>2</BlockThreshold>
<BlockThreshold>3</BlockThreshold>
<BlockThreshold>4</BlockThreshold>
<BlockThreshold>4</BlockThreshold>
</Thresholds>
</ThresholdMatrix>
</ElecTariffElements>
';
declare @idx int = 1;
declare @NumThresholds int = @xml.value('count(//*:ElecTariffElements/*:ThresholdMatrix/*:Thresholds/*:BlockThreshold)','int');
select @NumThresholds,@xml;
while (@idx <= @NumThresholds)
begin
set @xml.modify('replace value of (//*:ElecTariffElements/*:ThresholdMatrix/*:Thresholds/*:BlockThreshold/text())[sql:variable("@idx")][1] with 0');
select @xml;
set @idx = @idx + 1;
end
select @xml;