Monday, March 19, 2012

How to return the difference between simple xml on SQL Server 2005?

I have two simple xml as:
<row>
<a>1</a>
<b>3</b>
<c>5</c>
</row>
<row>
<a>2</a>
<b>3</b>
<c>7</c>
</row>
What statement can return the difference between xml as result as:
<row>
<a>Yes</a>
<b>No</b>
<c>Yes</c>
</row>-- This works, but it's ugly...
DECLARE @.x1 XML, @.x2 XML, @.x XML, @.xv varchar(MAX)
SET @.x1 = '<row><a>1</a><b>3</b><c>5</c></row>'
SET @.x2 = '<row><a>2</a><b>3</b><c>7</c></row>'
SET @.xv = ''
;WITH x1 AS
(SELECT
T.C.value('.', 'int') AS rowValue
, T.C.value('local-name(.)', 'varchar(10)') AS rowName
FROM @.x1.nodes('row/*') AS T(C))
,x2 AS
(SELECT
T.C.value('.', 'int') AS rowValue
, T.C.value('local-name(.)', 'varchar(10)') AS rowName
FROM @.x2.nodes('row/*') AS T(C))
SELECT @.xv = @.xv + ('<' + x1.rowName + '>'
+ CASE x1.rowValue WHEN x2.rowValue THEN 'Yes' ELSE 'No' END
+ '</' + x1.rowName + '>')
FROM x1 INNER JOIN x2 ON x1.rowName = x2.rowName
SELECT @.x = CAST('<row>' + @.xv + '</row>' AS XML)
SELECT @.x
Peter DeBetta, MVP - SQL Server
http://sqlblog.com
--
"ABC" <abc@.abc.com> wrote in message
news:ecz7aPjuHHA.1496@.TK2MSFTNGP06.phx.gbl...
>I have two simple xml as:
> <row>
> <a>1</a>
> <b>3</b>
> <c>5</c>
> </row>
>
> <row>
> <a>2</a>
> <b>3</b>
> <c>7</c>
> </row>
>
> What statement can return the difference between xml as result as:
> <row>
> <a>Yes</a>
> <b>No</b>
> <c>Yes</c>
> </row>
>|||Note: If we could dynamically construct elements, there would be a much
easier solution...
Peter DeBetta, MVP - SQL Server
http://sqlblog.com
--
"ABC" <abc@.abc.com> wrote in message
news:ecz7aPjuHHA.1496@.TK2MSFTNGP06.phx.gbl...
>I have two simple xml as:
> <row>
> <a>1</a>
> <b>3</b>
> <c>5</c>
> </row>
>
> <row>
> <a>2</a>
> <b>3</b>
> <c>7</c>
> </row>
>
> What statement can return the difference between xml as result as:
> <row>
> <a>Yes</a>
> <b>No</b>
> <c>Yes</c>
> </row>
>|||Thanks you for helpful, I think it can help me.
How about dynamically construct elements can be easiler solution?
"Peter W. DeBetta" <debettap@.hotmail.com> wrote in message
news:eP%23NzKQvHHA.3364@.TK2MSFTNGP02.phx.gbl...
> Note: If we could dynamically construct elements, there would be a much
> easier solution...
> --
> Peter DeBetta, MVP - SQL Server
> http://sqlblog.com
> --
> "ABC" <abc@.abc.com> wrote in message
> news:ecz7aPjuHHA.1496@.TK2MSFTNGP06.phx.gbl...
>

No comments:

Post a Comment