Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to convert xml out put of a TSQL query into varchar output

I am trying to generate

SELECT DISTINCT
        P.DOMAIN_ID,
        P.SOURCE_SYSTEM_ID
FROM    EDW.dbo.DOMAIN_VALUE AS P
WHERE   P.ID = 4
        AND CURRENT_FLAG = 'Y'
EXCEPT
( SELECT    F.DOMAIN_ID,
            F.SOURCE_SYSTEM_ID
  FROM      EDW.dbo.DOMAIN AS F
  WHERE     F.ID = 4
            AND F.CURRENT_FLAG = 'Y'
)
FOR     XML PATH('DOMAIN'),
            ROOT('DOMAIN_VALUE')  

The output value in XML in Result tab as

<REFERENCE_DOMAIN_VALUE>
   <REFERENCE_DOMAIN>
       <REFERENCE_DOMAIN_ID>10799</REFERENCE_DOMAIN_ID>
       <REFERENCE_SOURCE_SYSTEM_ID>7452-001</REFERENCE_SOURCE_SYSTEM_ID>
   </REFERENCE_DOMAIN>
</REFERENCE_DOMAIN_VALUE>

Now I need to convert this XML out to varchar(max) but the result needs to be same.

like image 273
prav Avatar asked Feb 22 '11 06:02

prav


1 Answers

Just subquery it into a scalar value and convert it. The trick here is that FOR XML in a subquery and EXCEPT on top don't mix, so subquery the EXCEPT part first.

SELECT CONVERT(varchar(max), (
    SELECT * FROM (
        SELECT DISTINCT P.DOMAIN_ID, P.SOURCE_SYSTEM_ID
        FROM EDW.dbo.DOMAIN_VALUE AS P
        WHERE P.ID = 4 AND CURRENT_FLAG = 'Y'
        EXCEPT (
        SELECT F.DOMAIN_ID, F.SOURCE_SYSTEM_ID
        FROM EDW.dbo.DOMAIN AS F
        WHERE F.ID = 4 AND F.CURRENT_FLAG = 'Y' )
    ) I
    FOR XML PATH('DOMAIN'), ROOT('DOMAIN_VALUE')
))
like image 72
RichardTheKiwi Avatar answered Sep 30 '22 01:09

RichardTheKiwi