Compare XML Values with existing table rows

I have a MS SQL Table containing user data, e.g. Username and ID. This list should be compared with another list which is available as XML Document. Fortunately MS SQL 2005 is able to process XML so I searched around and found a post from Divya Agrawal on In Divyas tip 2 XML files are compared, so I modified it to compare XML and SQL row.

For this example, my SQL Table ‘Users’ has just 2 rows: “Name” (varchar(100)) and “ID” (int). My XML File looks like this:

    <name>Thorsten Test</name>
    <name>Peter Pommes</name>
    <name>Wiki Pedia</name>

So I need to check whether ‘root/data/id’ from XML file is already in table column ‘ID’. If not, the name and the ID should be returned. This could be done with this little query:

CREATE PROCEDURE [dbo].[FindNewUsers]
  @Userlist XML
    Select N.value('name[1]', 'varchar(100)') as Username,
      N.value('id[1]', 'int') as ID
      from @Userlist.nodes('/root/data') as X(N)
      where N.value('id[1]', 'int') Not in (select ID from Users)


That’s it!

Leave a Comment