Search code examples
sqlsql-serverxmlt-sqlsqlxml

How can I get and compare two XML attributes using TSQL where the XML string is stored in a field?


I'm using SQL Server 2008 R2.

Imagine a table:

id | contentXml
1  | <node attr1='a' attr2='b' attr3='a'/>
2  | <node attr1='a' attr2='b' attr3='c'/>
3  | <node attr3='c' attr2='d' attr1='c'/>

The expected result should be a list of ID's where the value of attr1 and attr3 are the same. Note that the order of the attributes may be different like in the example above.

Result: 1 and 3


Solution

  • I think fastest way would be to use sqlxml exist() method:

    select
        t.id
    from Table1 as t
    where t.contentXml.exist('node[@attr1 = @attr3]') = 1
    

    It's also possible to do this with sqlxml value():

    select
        t.id
    from Table1 as t
    where
        t.contentXml.value('(node/@attr1)[1]', 'varchar(max)') =
        t.contentXml.value('(node/@attr3)[1]', 'varchar(max)')
    

    But this one would be slower.

    sql fiddle demo