Union in SQL while creating XML file

前端 未结 2 1781
清歌不尽
清歌不尽 2021-01-20 20:36

I got some problem with my SQL query which create a XML file. I want to do UNION it this query but it doesn\'t work.

(SELECT 1 AS \"ns0:kindOfIt         


        
2条回答
  •  不知归路
    2021-01-20 20:51

    You might be interested in this:

    Please compare the following

    The word "test" occurs in both lists. UNION will do a DISTINCT implicitly, so "test" appears only once.

    SELECT * 
    FROM (VALUES('this'),('is'),('a'),('test')) AS tbl(Words)
    UNION
    SELECT * 
    FROM (VALUES('and'),('another'),('test')) AS tbl(Words);
    

    The same with UNION ALL will let the "test" appear twice

    SELECT * 
    FROM (VALUES('this'),('is'),('a'),('test')) AS tbl(Words)
    UNION ALL
    SELECT * 
    FROM (VALUES('and'),('another'),('test')) AS tbl(Words);
    

    You can put your UNION SELECT into a surrounding SELECT (either UNION or UNION ALL and set the FOR XML PATH for the whole result-set

    The namespace is created repeatedly, not wrong, but annoying (see this: https://stackoverflow.com/a/35648751/5089204 and the linked Connect-Article)

    WITH XMLNAMESPACES(DEFAULT 'Dummy') 
    SELECT *
    FROM
    (
        SELECT * 
        FROM (VALUES('this'),('is'),('a'),('test')) AS tbl(Words)
        UNION
        SELECT * 
        FROM (VALUES('and'),('another'),('test')) AS tbl(Words)
    ) AS MetaTable
    FOR XML Path(''),ROOT('UNION_TEST');
    

    This will bring back both lists, each in its own XML tag, also repeated namespace (see before)

    WITH XMLNAMESPACES(DEFAULT 'Dummy') 
    SELECT
     (
        SELECT * 
        FROM (VALUES('this'),('is'),('a'),('test')) AS tbl(Words)
        FOR XML PATH(''),ROOT('FirstBlock'),TYPE
     )
    ,(
        SELECT * 
        FROM (VALUES('and'),('another'),('test')) AS tbl(Words)
        FOR XML PATH(''),ROOT('FirstBlock'),TYPE
     )
    FOR XML Path(''),ROOT('UNION_TEST');
    

    And finally you can use this too (either with ALL or not):

    WITH XMLNAMESPACES(DEFAULT 'Dummy') 
    SELECT * 
    FROM (VALUES('this'),('is'),('a'),('test')) AS tbl(Words)
    UNION ALL
    SELECT * 
    FROM (VALUES('and'),('another'),('test')) AS tbl(Words)
    FOR XML PATH(''),ROOT('UNION_TEST');
    

提交回复
热议问题