Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Create single XML from SQL Server multiple tables query

Tags:

sql-server

xml

I would like to query multiple tables from SQL Server 2005 and create a single XML document and do this in a stored procedure.

I know that I can query multiple tables within a stored procedure and get a DataSet in my .NET application that can be easily saved as XML. However, I'm trying to do something similar within the context of a stored procedure.

Essentially I want to do something like this:

declare @x xml
select @x = x.result
from (select y.* from tabley y for xml path('y')
      union
      select a.* from tablea a for xml path('aa')
     ) as x
select @x
like image 297
BermudaLamb Avatar asked Aug 09 '12 16:08

BermudaLamb


People also ask

How do I export data from SQL Server to XML?

If you want to export the whole SQL Server database to the XML file, you can first use the SQL Server Management Studio to export your SQL database to CSV, and then convert CSV to XML using an online converter. You ca also choose to output SQL Server database to Excel and then convert Excel (XLS) to XML.

How can a XML file be created from a database?

Here we are going to create an XML file from Database. Make an SQL connection to the Database and execute the sql and store the data in a Datset. Call Dataset's WriteXml() method and pass the file name as argument. You have to pass necessary database connection information to connection string.

How do I create an XML datatype in SQL?

You can use a DECLARE statement to create a variable of xml type, as the following example shows. DECLARE @x xml; Create a typed xml variable by specifying an XML schema collection, as shown in the following example.

Can we use the retrieve data from multiple tables?

In SQL, to fetch data from multiple tables, the join operator is used. The join operator adds or removes rows in the virtual table that is used by SQL server to process data before the other steps of the query consume the data.


1 Answers

If you want them just one after the other, you can try something like this:

SELECT
    (SELECT y.* FROM dbo.TableY FOR XML PATH('y'), TYPE) AS 'YElements',
    (SELECT a.* FROM dbo.TableA FOR XML PATH('aa'), TYPE) AS 'AElements'
FOR XML PATH(''), ROOT('root')

That return an XML something like:

<root>
   <YElements>
     <Y>
       ....
     </Y>
     <Y>
       ....
     </Y>
      ......
   </YElements>
   <AElements>
     <A>
       ....
     </A>
     <A>
       ....
     </A>
      ......
   </AElements>
</root>
like image 109
marc_s Avatar answered Sep 28 '22 01:09

marc_s