使用ROW_NUMBER更新XML元素

时间:2018-03-13 11:37:54

标签: sql xml

我有一个包含行号的表,然后是包含行号的XML,其中行号设置为1,如下所示:

<Policy>
  <PolicyRecordNumber>1</PolicyRecordNumber>
  <PCAdjustment>
    <PolicyNumber>XYZ00001</PolicyNumber>
    <EffectiveDate>2018-03-08T09:19:00</EffectiveDate>
</PCAdjustment>
</Policy>

每条记录都有自己的XML数据类型和XML代码。我希望使用每个记录的行号更新PolicyRecordNumber:

我试过这个

UPDATE tr1
SET XML.modify('replace value of (Policy/PolicyRecordNumber/text())[1] with "' + CONVERT(VARCHAR(10),tr1.[Record Number]) + '"')
FROM
(
    SELECT ROW_NUMBER() OVER (ORDER BY (SELECT NULL)) 'Record Number', t2.XML
    FROM dbo.Transmissions t2
    WHERE t2.XML_Valid = 1
) tr1

但是我收到关于字符串文字的投诉,我可以

UPDATE 
   dbo.Transmissions
SET 
    XML.modify('replace value of (Policy/PolicyRecordNumber/text())[1] with "5"')

但我必须同时指定相关行的ID并对行号进行硬编码,我需要对58行执行此操作,因此每个PolicyRecordNumber XML元素都会更新为1 - 58.

有人可以帮忙吗?

2 个答案:

答案 0 :(得分:0)

这解决了问题的原始版本。

我没有使用set xml.modify(),但我怀疑这会奏效:

UPDATE tr1
    SET XML.modify(updatestr)
    FROM (SELECT ROW_NUMBER() OVER (ORDER BY (SELECT NULL)) as seqnum,
                 ('replace value of (Policy/PolicyRecordNumber/text())[1] with "1"'
                 ) as updatestr,
                 t2.XML
          FROM dbo.Transmissions t2
          WHERE t2.XML_Valid = 1
         ) tr1
    WHERE tr1.seqnum = 1;

但这引出了一个问题。您坚持要将行号1,所以为什么不这样做:

UPDATE tr1
    SET XML.modify('replace value of (Policy/PolicyRecordNumber/text())[1] with "1"')
FROM (SELECT ROW_NUMBER() OVER (ORDER BY (SELECT NULL)) as seqnum, t2.XML
      FROM dbo.Transmissions t2
      WHERE t2.XML_Valid = 1
     ) tr1
WHERE seqnum = 1;

答案 1 :(得分:0)

假设这是SQL-Server,您可以使用sql:column()

DECLARE @mockupTable TABLE(ID INT IDENTITY, YourXML XML);
INSERT INTO @mockupTable VALUES
 ('<Policy><PolicyRecordNumber>1</PolicyRecordNumber></Policy>')
,('<Policy><PolicyRecordNumber>1</PolicyRecordNumber></Policy>')
,('<Policy><PolicyRecordNumber>1</PolicyRecordNumber></Policy>');

SELECT * FROM @mockupTable;

UPDATE @mockupTable SET YourXML.modify('replace value 
                                        of (/Policy/PolicyRecordNumber/text())[1] 
                                        with sql:column("ID")');
SELECT * FROM @mockupTable;

最终结果

ID  YourXML
1   <Policy><PolicyRecordNumber>1</PolicyRecordNumber></Policy>
2   <Policy><PolicyRecordNumber>2</PolicyRecordNumber></Policy>
3   <Policy><PolicyRecordNumber>3</PolicyRecordNumber></Policy>