Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to use FOR XML in Subqueries?

I'd like to return the below xml:

<ResultDetails>
<Node1>hello</Node1>
<Sites>
<Site><SiteId>1</SiteId></Site>
<Site><SiteId>2</SiteId></Site>
</Sites>
</ResultDetails>

I wrote the below code but doesn't work:

SELECT 'hello' AS Node1,    
    (SELECT TOP 2 SiteId
     FROM [dbo].[Sites]
       FOR XML PATH('Site')) AS Sites
FOR XML PATH('ResultDetails')

but it returns:

<ResultDetails>
  <row>
    <Node1>hello</Node1>
    <Sites>&lt;Site&gt;&lt;siteId&gt;102&lt;/siteId&gt;&lt;/Site&gt;&lt;Site&gt;&lt;siteId&gt;1&lt;/siteId&gt;&lt;/Site&gt;</Sites>
  </row>
</ResultDetails>

What sql should I write?

thanks,

like image 851
The Light Avatar asked Jul 30 '12 12:07

The Light


People also ask

Can we use functions in subqueries?

The trick to placing a subquery in the select clause is that the subquery must return a single value. This is why an aggregate function such as the SUM, COUNT, MIN, or MAX function is commonly used in the subquery.

What Cannot be included in a subquery?

You cannot include text, unitext, or image datatypes in subqueries. Subqueries cannot manipulate their results internally, that is, a subquery cannot include the order by clause, the compute clause, or the into keyword.

Can subqueries use joins?

Use a join or a subquery anytime that you reference information from multiple tables. Joins and subqueries are often used together in the same query. In many cases, you can solve a data retrieval problem by using a join, a subquery, or both.

Can we use where clause in subquery?

A subquery can be nested inside the WHERE or HAVING clause of an outer SELECT , INSERT , UPDATE , or DELETE statement, or inside another subquery.


1 Answers

You need to add the TYPE modifier to your inner query:

SELECT
    'hello' AS Node1
    , (
        SELECT TOP 2 SiteId 
            FROM [dbo].[Sites] 
        FOR XML PATH('Site'), TYPE
    ) AS Sites 
FOR XML PATH('ResultDetails') 
like image 58
podiluska Avatar answered Sep 19 '22 11:09

podiluska