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

StackOverflow https://stackoverflow.com/questions/20092187

سؤال

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

هل كانت مفيدة؟

المحلول

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

نصائح أخرى

Here you have a different approach:

SELECT id, 
       t.contentXml.value('(/node/@attr1)[1]','nvarchar(max)'),
       t.contentXml.value('(/node/@attr3)[1]','nvarchar(max)')
FROM Table1 t
WHERE t.contentXml.value('(/node/@attr1)[1]','nvarchar(max)') = t.contentXml.value('(/node/@attr3)[1]','nvarchar(max)')

And working sql code on SQL Fiddle

Result:

id
1   a   a
3   c   c
مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top