Search code examples
sql-serverxmlxqueryxquery-sqlflwor

Return multiple XML nodes and Custom parent tag using FLWOR XQuery


I need to get the following output using a FLWOR expression.

<oldPlanes>
  <make>Cessna</make>
  <model>Centurian</model>
  <make>Piper</make>
  <model>Tripacer</model>
</oldPlanes>

using

CREATE TABLE XMLO1 (xDoc XML NOT NULL)

INSERT INTO XMLO1 VALUES ('
 <planes>
   <plane>
     <year>1977</year>
     <make>Cessna</make>
     <model>Skyhawk</model>
     <color>Light blue and white</color>
   </plane>
   <plane>
     <year>1975</year>
     <make>Piper</make>
     <model>Apache</model>
     <color>White</color>
   </plane>
   <plane>
     <year>1960</year>
     <make>Cessna</make>
     <model>Senturian</model>
     <color>Yellow and White</color>
   </plane>
   <plane>
     <year>1956</year>
     <make>Piper</make>
     <model>ripacer</model>
     <color>Blue</color>
   </plane>
 </planes>')

I tried the below query

SELECT xDoc.query('for $p in //plane
                    let $x:=$p/year
                    where $x < 1970
                    return <oldPlanes><make>{data($p/make)}</make> 
                           </oldPlanes>
                    ')
FROM XMLO1

This doesn't gives me the expected output to find the planes where Year < 1970.

How to set a custom parent node as <oldPlanes>

How to return 2 nodes as the expected output?


Solution

  • You only want to create one oldPlanes element so its construction needs to be outside the FLWOR expression:

    <oldPlanes>{for $p in //plane
                let $x:=$p/year
                where $x < 1970
                return $p/(make, model)}</oldPlanes>
    

    Except that you don't need a FLWOR for this at all, a simple path expression will do the job:

    <oldPlanes>{//plane[year < 1970]/(make, model)}</oldPlanes>