I have a table that includes Row Numbers and then subsequently XML that contains a Row Number that is set to 1 like so:
<Policy>
<PolicyRecordNumber>1</PolicyRecordNumber>
<PCAdjustment>
<PolicyNumber>XYZ00001</PolicyNumber>
<EffectiveDate>2018-03-08T09:19:00</EffectiveDate>
</PCAdjustment>
</Policy>
Each record has its own XML data type, and XML code. I wish to update the PolicyRecordNumber with the Row Number for each record:
I tried doing this
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
However I get a complaint about a string literal, I can get
UPDATE
dbo.Transmissions
SET
XML.modify('replace value of (Policy/PolicyRecordNumber/text())[1] with "5"')
working however I have to specify both the ID for the row in question and also hard-code the row number, I need to do this for 58 rows so each PolicyRecordNumber XML Element is updated with 1 - 58.
Can anyone assist?
THIS ADDRESSES THE ORIGINAL VERSION OF THE QUESTION.
I have not use set xml.modify()
, but I suspect this will work:
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;
But this begs the question. You are insisting that the row number be 1
, so why not just do:
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;
Assuming this is SQL-Server you can use 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;
The final result
ID YourXML
1 <Policy><PolicyRecordNumber>1</PolicyRecordNumber></Policy>
2 <Policy><PolicyRecordNumber>2</PolicyRecordNumber></Policy>
3 <Policy><PolicyRecordNumber>3</PolicyRecordNumber></Policy>
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.