Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to return multiple tables as one XML?

I have the following script:

DECLARE @columns TABLE (
    Caption varchar(50),
    Width int);

INSERT INTO @columns 
VALUES ('Id', 0), ('Name', 100);

DECLARE @rows TABLE (
    Id int,
    [Name] varchar(50));

INSERT INTO @rows 
VALUES (1, 'John'), (2, 'Steve');

SELECT *,
    (SELECT *
     FROM @rows
     FOR XML PATH('Row'), ROOT('Rows'), TYPE, ELEMENTS)
FROM @columns
FOR XML PATH('Column'), ROOT('Results'), TYPE, ELEMENTS;

And I need to return the following XML:

<Results>
    <Columns>
        <Column>
            <Caption>Id</Caption>
            <Width>0</Width>
        </Column>
        <Column>
            <Caption>Name</Caption>
            <Width>100</Width>
        </Column>
    </Columns>
    <Rows>
        <Row>
            <Id>1</Id>
            <Name>John</Name>
        </Row>
        <Row>
            <Id>2</Id>
            <Name>Steve</Name>
        </Row>
    </Rows>
</Results>

The idea is that I will convert the XML into a DataSet with 2 DataTables (one for Columns and the other for Rows). I will use this to populate a DataGridView.

However, my problem is that the XML I'm generating currently is malformed and isn't the same as I'm expecting.

What is the correct syntax to generate the XML as expected?

like image 914
Ivan-Mark Debono Avatar asked Jan 24 '19 09:01

Ivan-Mark Debono


2 Answers

This gets you the result you want, based on the data we have:

SELECT (SELECT Caption,
               Width
        FROM @columns
        FOR XML PATH('Column'),TYPE) AS [Columns],
       (SELECT Id,
               [Name]
        FROM @rows
        FOR XML PATH('Row'),TYPE) AS [Rows]
FOR XML PATH ('Results');
like image 62
Larnu Avatar answered Oct 19 '22 18:10

Larnu


This query generates exactly the result you're expected:

SELECT (SELECT clm.Caption,
               clm.Width
        FROM @columns clm
        FOR XML PATH('Column'), TYPE) AS Columns,
       (SELECT rs.Id,
               rs.[Name]
        FROM @rows rs
        FOR XML PATH('Row'),TYPE) AS [Rows]
FOR XML PATH ('Results');
like image 2
Saman Gholami Avatar answered Oct 19 '22 19:10

Saman Gholami