Delete nodes with certain value from XML using TSQL
Asked Answered
C

2

12

I'm trying to parse a piece of XML and remove nodes that contain certain values. I know how to remove them if the value is exact, but I want to use something like a "contains".

This works to delete exactly:

update @XML set data.modify('delete //Message[text() = "customer has deleted their account"]')

But I want to delete where the "Message" node just contains the text, something like:

update @XML set data.modify('delete //Message[contains(text(), "customer")]')

However this returns the error:

XQuery [@XML.data.modify()]: 'contains()' requires a singleton (or empty sequence), found operand of type 'xdt:untypedAtomic *'
Cinerama answered 25/2, 2013 at 16:48 Comment(0)
B
23

Try

update @XML set data.modify('delete //Message[text()][contains(.,"customer")]')

to delete the <message/> element and its contents

update @XML set data.modify('delete //Message//text()[contains(.,"customer")]')

to delete the <message/> element's contents.

Example here http://msdn.microsoft.com/en-us/library/ms178026.aspx

Bluecoat answered 25/2, 2013 at 18:28 Comment(1)
Prefect. I'd got to something very similar, but it was a 2 step. Delete the contents of the node, and then delete empty nodes. This is much more elegant.Cinerama
R
6
    declare @XML xml = '
    <Root>
      <Sub>
        <Record>
          <Guid>aslkjflaksjflkasjfkljsd</Guid>
        </Record>
        <Record>
           <Guid>opqiwuerl;kasdlfkjawop</Guid>
        </Record>
      </Sub>
    </Root>'

declare @Guid varchar(30) = 'aslkjflaksjflkasjfkljsd'

set @XML.modify('delete /Root/Sub/Record[Guid = sql:variable("@Guid")]')

Reference https://dba.stackexchange.com/questions/40039/how-to-return-xml-node-ordinal-or-delete-node-based-on-element-value

Refer answered 12/1, 2017 at 11:11 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.