简体   繁体   中英

Join a generated XML Column (from sub query) to parent Query

I am working on an existing query which currently joins a number of tables but also joins on to sub-query. Something like what i have shown below:

SELECT p.*
FROM Product as p
LEFT JOIN (
SELECT pl.*
FROM ProductList
WHERE .....) as pl
ON p.id = pl.productId
WHERE....

Now there are more tables than this in the actual query and more conditions but i just want to focus in on the problem.

What we want is for the inner query (on ProductList) to return as XML and of course join it to the correct row on the top level table.

I would guess something like this

SELECT top 10 p.*
FROM Catalogue.Product as p
LEFT JOIN (
SELECT TOP 10 *
FROM Catalogue.ProductListItem
FOR XML RAW('Product'), ROOT('Products'), ELEMENTS
) as pl
ON p.productid = salespart.nodes('Products/Product/ProductId')

Can you help?

Not really clear what you want your output to be but I guess the best for you would be to use a correlated sub-query in the field list that builds the XML from Catalogue.ProductListItem for each product.

select p.*,
       (
         select pl.*
         from Catalogue.ProductListItem as pl
         where pl.ProductID = p.ProductID
         for xml raw('Product'), root('Products'), elements, type
       ) as ProductXML
from Catalogue.Product as p

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM