Compare Xml data in SQL

醉酒当歌 提交于 2019-12-14 03:54:20

问题


I have two tables with same NVARCHAR field that really contains XML data. in some cases this really-XML-field is really same as one row in other table but differs in attributes order and therefor string comparison does not return the correct result!!!

and to determining the same XML fields ,I need to have a comparison like:

  cast('<root><book b="" c="" a=""/></root>' as XML) 
= cast('<root><book a="" b="" c=""/></root>' as XML)

but I get this Err Msg:

The XML data type cannot be compared or sorted, except when using the IS NULL operator.

then what is the best solution to determine the same XML without re-casting them to NVARCHAR?


回答1:


Why cast it at all? Just plug them into an XML column in a temp table and run Xquery to compare them to the other table. EDIT: Included example of the comparison. There are many, many ways to run the query against the XML to get the rows that are the same - exactly how that query is written is going to depend on preference, requirements, etc. I went with a simple group by/count, but a self join could be used, WHERE EXISTS against the columns that are being searched for duplicates, you name it.

CREATE TABLE #Test (SomeXML NVARCHAR(MAX))
CREATE TABLE #XML (SomeXML XML)

INSERT #Test (SomeXML)
VALUES('<root><book b="b" c="c" a="a"/></root>')
    ,('<root><book a="a" b="b" c="c"/></root>')

INSERT #XML (SomeXML)

SELECT SomeXML FROM #Test;

WITH XMLCompare (a,b,c)
AS
(
SELECT 
    x.c.value('@a[1]','char(1)') AS a
    ,x.c.value('@b[1]','char(1)') AS b 
    ,x.c.value('@c[1]','char(1)') AS c  
FROM #XML
CROSS APPLY SomeXMl.nodes('/root/book') X(C)
)

SELECT 
    a
    ,b
    ,c
FROM XMLCompare as a
GROUP BY
    a
    ,b
    ,c
HAVING COUNT(*) >1


来源:https://stackoverflow.com/questions/7428587/compare-xml-data-in-sql

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!