[英]SQL Server XML-DML how to replace element value with value of relative xpath
我有一個包含以下數據的xml列:
<Policy>
<Name>
<Id>adf</Id>
<First>Alan</First>
<Last>Turing</Last>
</Name>
<Name>
<Id>asdf</Id>
<Business>Vandelay Industries</Business>
</Name>
<Name>
<Id>asdf</Id>
<First>Dennis</First>
<Last>Ritchie</Last>
</Name>
</Policy>
我將如何編寫XML-DML查詢,該查詢將替換所有行中每個Name的Id元素的值,因此它包含First,Last和Business的值。 例如:
<Policy>
<Name>
<Id>AlanTuring</Id>
<First>Alan</First>
<Last>Turing</Last>
</Name>
<Name>
<Id>Vandelay Industries</Id>
<Business>Vandelay Industries</Business>
</Name>
<Name>
<Id>DennisRitchie</Id>
<First>Dennis</First>
<Last>Ritchie</Last>
</Name>
</Policy>
這是我失敗的嘗試:
update policy set data.modify('
replace value of (//Name/Id/text())[1]
with concat(
(//Name/First/text())[1],
(//Name/Last/text())[1],
(//Name/Business/text())[1])')
產生以下內容:
<Policy>
<Name>
<Id>AlanTuringVandelay Industries</Id>
<First>Alan</First>
<Last>Turing</Last>
</Name>
<Name>
<Id>asdf</Id>
<Business>Vandelay Industries</Business>
</Name>
<Name>
<Id>asdf</Id>
<First>Dennis</First>
<Last>Ritchie</Last>
</Name>
</Policy>
這可行。
declare @i int
declare @maxNames int
set @i = 1
set @maxNames = (select max(data.value('count(//Name)', 'int')) from Policy)
while @i <= @maxNames begin
update policy set data.modify('
replace value of (//Name[sql:variable("@i")]/Id/text())[1]
with concat(
(//Name[sql:variable("@i")]/First/text())[1],
(//Name[sql:variable("@i")]/Last/text())[1],
(//Name[sql:variable("@i")]/Business/text())[1])
')
set @i = @i + 1
end
一個基於集合的選項就是這個:
update policy
set data.modify('
replace value of (//Name[sql:column("id")]/Id/text())[1]
with concat(
(//Name[sql:column("id")]/First/text())[1],
(//Name[sql:column("id")]/Last/text())[1],
(//Name[sql:column("id")]/Business/text())[1])
')
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.