0

In my SQL Server DB I have table with an XML column. The XML that goes in it is like the sample below:

<Rows>
      <Row>
           <Name>John</Name>
      </Row>
      <Row>
           <Name>Debbie</Name>
      </Row>
      <Row>
           <Name>Annie</Name>
      </Row>
      <Row>
           <Name>John</Name>
      </Row>
</Rows>

I have a requirement that I need to find the occurrence of all rows where the XML data has duplicate entries of <Name>. For example, above we have 'John' twice in the XML.

I can use the exist XML statement to find 1 occurrence, but how can I find if it's more than 1? Thanks.

2 Answers 2

1

To identify any table row that has duplicate <Name> values in its XML, you can use exist as well:

exist('//Name[. = preceding::Name]')

To identify which names are duplicates, respectively, you need nodes and CROSS APPLY

SELECT
  t.id,
  x.Name.value('.', 'varchar(100)') AS DuplicateName
FROM
  MyTable t
  CROSS APPLY t.MyXmlColumn.nodes('//Name[. = preceding::Name]') AS x(Name)
WHERE
  t.MyXmlColumn.exist('//Name[. = preceding::Name]')
Sign up to request clarification or add additional context in comments.

Comments

1

Try this:

;with cte as
(SELECT tbl.col.value('.[1]', 'varchar(100)') as name
 FROM   yourtable
 CROSS APPLY xmlcol.nodes('/Rows/Row/Name') as tbl(col))

select name
from cte
group by name
having count(name) > 1

We first use the nodes function to convert from XML to relational data, then use value to get the text inside the Name node. We then put the result of the previous step into a CTE, and use a simple group by to get the value with multiple occurences.

Demo

1 Comment

@Tomalak Yeah it supports a lot of languages and even has autocomplete for C#. Very handy!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.