Skip to content
Related Articles
Open in App
Not now

Related Articles

SQL Server | Convert tables in T-SQL into XML

Improve Article
Save Article
  • Last Updated : 09 Mar, 2021
Improve Article
Save Article

In this, we will focus on how tables will be converted in T-SQL into XML in SQL server. And you will be able to understand how you can convert it with the help of command. Let’s discuss it one by one.

Overview :
XML (Extensible Markup Language) is a markup language similar to HTML which was designed to share information between different platforms. And here, you will understand how you can Convert tables in T-SQL into XML.

Example –
Here is a below sample XML Document as follows.

 <heading>Work Status</heading>
 <body>Work Completed</body>

Converting tables in T-SQL into XML :
To Convert tables in T-SQL into XML by using the following steps as follows. Let’s first generate an Employee_Table to store data of few Employees in order to create XML documents. 

Creating table – Employee_Table 

CREATE TABLE Employee_Table  
EmpId int identity(1,1) primary key,  
Name varchar(100),  
Salary int ,  
City varchar(20)  

Inserting data into Employee_Table –

insert into Employee_Table ( Name,City,Salary)

Reading data to verify –

SELECT * FROM Employee_Table

Output :

Methods of converting tables in T-SQL into XML :
There are two common ways to convert data from SQL tables into XML format as follows.

The FOR XML AUTO class creates an XML document where each column is an attribute.

SELECT * FROM Employee_Table

Output :

This query will create a hyperlink as an output. On clicking the link, we will see the following document in a new query window of SSMS as follows.

With FOR XML PATH clauses –
FOR XML PATH will create an XML document where each row is embedded into <row> and </row> clause. In each row, each column value is embedded into <ColumnName> and </ColumnName> clauses.


Output :

My Personal Notes arrow_drop_up
Related Articles

Start Your Coding Journey Now!