SQL SERVER – Simple Example of Creating XML File Using T-SQL

I always want to learn SQL Server and XML file. Let us go over a very simple example, today about how to create XML using SQL Server.

Please also read related article here SQL SERVER – Simple Example of Reading XML File Using T-SQL.

Following is the XML which we want to create:

SQL SERVER - Simple Example of Creating XML File Using T-SQL samplexml

T-SQL Script to generate above XML:

SELECT ( SELECT 'White' AS Color1,
'Blue' AS Color2,
'Black' AS Color3,
'Light' AS 'Color4/@Special',
'Green' AS Color4,
'Red' AS Color5
FOR
XML PATH('Colors'),
TYPE
),
( SELECT 'Apple' AS Fruits1,
'Pineapple' AS Fruits2,
'Grapes' AS Fruits3,
'Melon' AS Fruits4
FOR
XML PATH('Fruits'),
TYPE
)
FOR XML PATH(''),
ROOT('SampleXML')
GO

SQL SERVER - Simple Example of Creating XML File Using T-SQL samplexml1

Every XML has two elements.

1) Attributes and 2) Value.

In my above example color4 has attribute along with value. Make sure to specify attribute before the value is defined otherwise it will give error. We will talk about this in another article. XML data is known as self-describing or self-defining, meaning that the structure of the data is embedded with the data, thus when the data arrives there is no need to pre-build the structure to store the data; it is dynamically understood within the XML.

Reference: Pinal Dave (https://darkslategrey-bat-805937.hostingersite.com)

SQL Scripts, SQL Server, SQL XML
Previous Post
SQL SERVER – Technical Articles – Performance Optimizations for the XML Data Type in SQL Server 2005
Next Post
SQL SERVER – Simple Example of Reading XML File Using T-SQL

Related Posts

Leave a Reply