Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

TSQL Delete XML node if its child element contains a given value

Tags:

tsql

xml

XML Storage can have zero or more <Address> nodes under <Addresses> Need a query to delete any <Address> nodes whose <AddressLine> = '2 Church Lane'

Starting XML:

declare @t table (storage xml);
insert into @t (storage)
select '<Person>
  <Fullname />
  <Surname>Smith</Surname>
  <FirstName>John</FirstName>
  <Addresses>
      <Address>
        <AddressLine>1 Church Lane</AddressLine>
      </Address>
      <Address>
        <AddressLine>2 Church Lane</AddressLine>
      </Address>
      <Address>
        <AddressLine>3 Church Lane</AddressLine>
      </Address>
  </Addresses>
</Person>';

Resulting XML:

<Person>
  <Fullname />
  <Surname>Smith</Surname>
  <FirstName>John</FirstName>
  <Addresses>
      <Address>
        <AddressLine>1 Church Lane</AddressLine>
      </Address>
      <Address>
        <AddressLine>3 Church Lane</AddressLine>
      </Address>
  </Addresses>
</Person>
like image 372
chrismat Avatar asked Jan 01 '14 00:01

chrismat


1 Answers

Found it:

update @t
SET storage.modify('
    delete (/Person/Addresses/Address[AddressLine = "2 Church Lane"])
')
like image 87
chrismat Avatar answered Oct 11 '22 11:10

chrismat