简体   繁体   中英

XML query/modify problem in SQL server 2008 r2

I'm fairly new to SQL and I'm trying to filter and change the values inside of column that holds an XML document for a purchased order. Here's an example of what the XML document looks like and what I'm searching for.

 <TenderLines>
   <TenderLineItem>
     <tenderTypeId>S0001-00000001</tenderTypeId>
     ..
     ..
    </TenderLineItem>
  <TenderLines>

I've got 6000+ rows and not all of them have the same tenderTypeId. I want to filter out the values in tenderTypeId that have 'S0001-00000001' and change them to '2'

So far this is what I've come up with.

USE LSPOS80
DECLARE @replacement as varchar(50)
DECLARE @redundant as varchar(50)
SET @replacement = '2'
SET @redundant = 'S0001-00000001'

Update dbo.POSISTRANSACTIONTABLE
SET TRANSACTIONXML.modify
('replace value of(/RetailTransaction/TenderLines/TenderLineItem/tenderTypeId/@redundant) [1] with sql:variable("@replacement")')

The query is executed successfully but nothing changes and I was wondering if any of you could read over this and possibly give me tips.

Thanks for your time, with best regards, Valdi.

PS I'm using Microsoft SQL Server 2008 R2 - Express Edition

update dbo.POSISTRANSACTIONTABLE set
  TRANSACTIONXML.modify('replace value of (/TenderLines/TenderLineItem/tenderTypeId/text())[1] with (sql:variable("@replacement"))')
where XMLCol.exist('/TenderLines/TenderLineItem/tenderTypeId[. = sql:variable("@redundant")]') = 1

Something to test on:

declare @T table(XMLCol xml)
insert into @T values 
('<TenderLines>
   <TenderLineItem>
     <tenderTypeId>S0001-00000001</tenderTypeId>
    </TenderLineItem>
 </TenderLines>'),
('<TenderLines>
   <TenderLineItem>
     <tenderTypeId>S0003-00000003</tenderTypeId>
    </TenderLineItem>
 </TenderLines>')

DECLARE @replacement as varchar(50)
DECLARE @redundant as varchar(50)
SET @replacement = '2'
SET @redundant = 'S0001-00000001'

update @T set
  XMLCol.modify('replace value of (/TenderLines/TenderLineItem/tenderTypeId/text())[1] with (sql:variable("@replacement"))')
where XMLCol.exist('/TenderLines/TenderLineItem/tenderTypeId[. = sql:variable("@redundant")]') = 1

select *
from @T

Note that this will only replace one value of tenderTypeId in the XML for each row. If you have multiple tenderTypeId's in the xml (in one row) and you want to replace them all you need to put the update statement in a while loop and replace as long as where XMLCol.exist('/TenderLines/TenderLineItem/tenderTypeId[. = sql:variable("@redundant")]') = 1 .

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM