What is OpenXML

Advantages of Using OPENXML

OPENXML limitations

OPENXML is very memory intensive. The pointer returned by the system stored procedure sp_xml_preparedocument is a memory pointer to a COM XML document object model. So, you must be careful not to load very large XML documents into memory with OPENXML because it may overload your server's memory.
Example 1- Inserting records from XMLDoc to sql table
  1. DECLARE @h int
  2. DECLARE @xmldoc VARCHAR(1000)
  3. --xmldoc is set with the xml elements which are to be inserted into the table students with FirstName,ID,Technology as table columns
  4. SET @xmldoc =
  5. '<root>
  6. <student FirstName="Ravi" ID="1" Technology="DotNet"></student>
  7. <student FirstName="Avdesh" ID="2" Technology="DotNet"></student> </root>'
  8. EXEC sp_xml_preparedocument @h OUTPUT, @xmldoc
  9. --This sp_xml_preparedocument is internal server SP (pseudo SP). which takes the xmldoc as input and gives an output in @h which contains the data which is to be manipulated further
  10. INSERT INTO student
  11. SELECT * FROM OpenXML(@h,'/root/student')
  12. WITH student
  13. EXEC sp_xml_removedocument @h
  14. --sp_xml_removedocument free's up the memory.
Output
outputOpenXml.bmp
sp_xml_preparedocument can only process text or untyped XML. If an instance value to be used as input is already typed XML, first cast it to a new untyped XML instance or as a string and then pass that value as input.
A parsed document is stored in the internal cache of SQL Server. To avoid running out of memory, run sp_xml_removedocument to free up the memory.
Example 2 - Updating records from XMLDoc to sql table
  1. DECLARE @h int
  2. DECLARE @xmldoc VARCHAR(1000)
  3. --xmldoc is set with the xml elements which are to be inserted into the table students with FirstName,ID,Technology as table columns
  4. SET @xmldoc =
  5. '<root>
  6. <student FirstName="Ravi Sharma" ID="1" Technology="DotNet"></student> <student FirstName="Avdesh" ID="2" Technology="DotNet"></student> </root>'
  7. EXEC sp_xml_preparedocument @h OUTPUT, @xmldoc
  8. --This sp_xml_preparedocument is internal server SP (pseudo SP). which takes the xmldoc as input and gives an output in @h which containd the data which is to be manipulated further
  9. UPDATE student
  10. SET
  11. FirstName = x.FirstName
  12. ,ID = x.ID
  13. ,Technology = x.Technology
  14. FROM OpenXML(@h,'/root/student')
  15. WITH (FirstName nvarchar(20),ID nvarchar(20),Technology nvarchar(20)) x where student.ID='1'
  16. EXEC sp_xml_removedocument @h
  17. --sp_xml_removedocument free's up the memory.
  18. select * from student
Output
outputOPenXmlUpd.bmp