Search code examples
sqlsql-serverxmlxqueryroot

How can I add constants to my root in XML?


This is my query that generates an XML:

SELECT [a]                             a
      ,[b]                             b
      ,[c]                             c
      ,[d]                             d
      ,[e]                             e
      ,[f]                             f
      ,[g]                             g
  FROM test
  ORDER BY 1
  FOR XML PATH('a'), ROOT('ROOT'), ELEMENTS XSINIL

The XML generated starts with this root:

<ROOT xmlns:xsi="http://www.xxxxxxxxxxxxxxxxxxxxxx">

My goal is to have a root with more attributes

<ROOT xmlns:xsi="http://www.xxxxxxxxxxxxxxxxxxxxxx" cod_1="SIN_OPE" cod_2="08" num_reg="12" xsi:noNamespaceSchemaLocation="yyyyyyyyyyyyyyyyyyy.xsd">

This attributes are like constants (thet are not columns from select) that I want to append to my root. They will be fixed, whatever will be the select

Is it possible to do it?


Solution

  • Here is a conceptual example. Please give it a shot.

    SQL

    -- DDL and sample data population, start
    DECLARE @tbl TABLE (ID INT IDENTITY PRIMARY KEY, city VARCHAR(30));
    INSERT INTO @tbl (city) VALUES
    ('Miami'),
    ('Orlando');
    -- DDL and sample data population, end
    
    SELECT 'SIN_OPE' AS [@cod_1], '08' AS [@cod_2], '12' AS [@num_reg]
        , 'yyyyyyyyyyyyyyyyyyy.xsd' AS [@xsi:noNamespaceSchemaLocation]
    , (
        SELECT * 
        FROM @tbl
        FOR XML PATH('r'), TYPE
    )
    FOR XML PATH('root'), TYPE, ELEMENTS XSINIL;
    

    Output

    <root xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" cod_1="SIN_OPE"
          cod_2="08" num_reg="12"
          xsi:noNamespaceSchemaLocation="yyyyyyyyyyyyyyyyyyy.xsd">
        <r>
            <ID>1</ID>
            <city>Miami</city>
        </r>
        <r>
            <ID>2</ID>
            <city>Orlando</city>
        </r>
    </root>