The Openxml function provides a rowset view over an XML document. This function is the system function which provides a rowset. The OPENXML function allows the data in a XML document to be treated just like the columns and rows of your database table. The function is used with the sp_xml_preparedocument stored system procedure. So let's have a look at a practical example of how to perform an operation using it in SQL Server. The example is developed in SQL Server 2012 using the SQL Server Management Studio.

Syntax

The Syntax of the Openxml system function is as follows:

openxml ( idoc int [ in] , rowpattern nvarchar [ in ],
[ flags byte [ in ] ] )
[ with ( SchemaDeclaration | TableName ) ]

Here, The meaning of each element in the preceding description is as follows:

idoc parameter - Used for the XML document and to handle the XML document.

rowpattern - To identify the nodes of an XML document.

flags - A set of flags indicating how the rowset columns are mapped to the attributes and elements. The flags value can be any of the following:

The advantages of using the OPENXML Function are:

Example

DECLARE @xmlDtype NVARCHAR(200)

DECLARE @h INT

SET @xmlDtype = N'

<Book>

<Id>1</Id>

<Author>Smith</Author>

<Title>SQL for Beginners</Title>

</Book>'

-- Creating XML Documents

Exec sp_xml_preparedocument @h OUTPUT, @xmlDtype

-- SELECT statement using OPENXML rowset provider

SELECT * FROM OPENXML (@h, '/Book', 2) WITH

(Id VARCHAR(20),

Author NVARCHAR(20),

Title NVARCHAR(20)

)

OUTPUT

OpenXML-Function-in-SQL-Server.jpg

Inserting Records From XMLDoc to SQL Table

DECLARE @xmlDtype NVARCHAR(200)

DECLARE @h INT

SET @xmlDtype = N'

<Book>

<Id>1</Id>

<Author>Smith</Author>

<Title>SQL for Beginners</Title>

</Book>'

-- Creating XML Documents

Exec sp_xml_preparedocument @h OUTPUT, @xmlDtype

-- SELECT statement using OPENXML rowset provider

insert into Book SELECT * FROM OPENXML (@h, '/Book', 2) WITH

(Id VARCHAR(20),

Author NVARCHAR(20),

Title NVARCHAR(20)

)

Go

Select * from Book

OUTPUT

OpenXML-Function-with-insert-statement-in-SQL-Server.jpg