2

我有一个包含以下数据的 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>
4

2 回答 2

3

这行得通。

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
于 2012-01-20T15:54:26.950 回答
1

一个基于集合的选项将是这个:

    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])
    ') 
于 2015-11-23T22:43:08.990 回答