Alex Alex - 4 months ago 16
SQL Question

How to compare two xml files in mssql

I have 2 files of type :

@xmlAuthors1 XML =N'
<Author name="John" surname="Clinton" />
<Author name="Bill" surname="Skobov" />
<Author name="John" surname="Lokwood" />;

@xmlAuthors2 XML =N'
<Author name="Bill" surname="Skobov" />
<Author name="John" surname="Clinton" />
<Author name="John" surname="Lokwood" />;


how do find out that they are equal? compare each line of the file 1 with each line from of the file 2

Answer

For example you can compare them like:

DECLARE @xmlAuthors1 XML = N'
               <Author name="John" surname="Clinton" />
               <Author name="Bill" surname="Skobov" />
               <Author name="John" surname="Lokwood" />',
        @xmlAuthors2 XML =N'
               <Author name="Bill" surname="Skobov" />
               <Author name="Johns" surname="Clinton" />
               <Author name="John" surname="Lokwood" />'


SELECT *
FROM (
    SELECT  CAST(x1.t.query('.') as nvarchar(max)) as x1,
            CAST(x2.t.query('.') as nvarchar(max)) as x2
    FROM @xmlAuthors1.nodes('/*') as x1(t)
    FULL OUTER JOIN @xmlAuthors2.nodes('/*') as x2(t)
        ON CAST(x1.t.query('.') as nvarchar(max)) = CAST(x2.t.query('.') as nvarchar(max))
) as x
WHERE x1 is null or x2 is null

If there are equal there will be no output

Comments