2011-09-29 90 views
0

我想要替換XML中屬性的值。該屬性在xml中多次出現。我怎麼能代替這些一次性SQL Server XML替換屬性中的值

我的XML lools一些什麼樣的如下:

<Example> 
    <A> 
    <B Type = "x">qqq</B> 
    <B Type = "x">www</B> 
    </A> 
    <C> 
    <D Type = "x">aaa</D> 
    <D Type = "x">uuu</D> 
    </C> 
</Example> 

我想Ÿ

回答

1

全部更換x你不能代替一次性使用replace value of (XML DML)。你必須循環做。

declare @xml xml = ' 
<Example> 
    <A> 
    <B Type = "x">qqq</B> 
    <B Type = "x">www</B> 
    </A> 
    <C> 
    <D Type = "x">aaa</D> 
    <D Type = "x">uuu</D> 
    </C> 
</Example> 
' 

while (select @xml.exist('//*[@Type = "x"]')) = 1 
begin 
    set @xml.modify('replace value of (//*[@Type = "x"]/@Type)[1] with "y"') 
end 

select @xml 

結果:

<Example> 
    <A> 
    <B Type="y">qqq</B> 
    <B Type="y">www</B> 
    </A> 
    <C> 
    <D Type="y">aaa</D> 
    <D Type="y">uuu</D> 
    </C> 
</Example> 

更新

替換值X和Z與Y:

while (select @xml.exist('//*[@Type = ("x","z")]')) = 1 
begin 
    set @xml.modify('replace value of (//*[@Type = ("x","z")]/@Type)[1] with "y"') 
end 

,其中y替換所有值:

while (select @xml.exist('//*[@Type != "y"]')) = 1 
begin 
    set @xml.modify('replace value of (//*[@Type != "y"]/@Type)[1] with "y"') 
end 
+0

嗨Mikael,謝謝你的答案,這很好,但我在這裏有另一個問題,在每個元素的類型屬性是不同的,例如在整個元素A,它是X和整個Elemnt B它是Z和我必須用y代替所有z和x ..我怎麼能這樣做... – Santy

+0

@Santy - 用一些替代方案更新了答案。 –