I'm studying XML/SQL and have the following question. I would like to shred XML data into a table. but my question is: I have many authors using the same tag (<author>
) inside the same book category. I would like to select ALL the authors, but I can't achieve this point. Could you please help me to do that?
The result should look like:
category title author author1 author2
=============================================================================
CHILDREN Harry Potter J K. Rowling NULL NULL
WEB XQuery Kick Start James McGovern Per Bothner Kurt Cagle
Code:
declare @int int
declare @var xml = '<?xml version="1.0" encoding="ISO-8859-1"?>
<bookstore>
<book category="CHILDREN">
<title lang="en">Harry Potter</title>
<author>J K. Rowling</author>
<year>2005</year>
<price>29.99</price>
</book>
<book category="WEB">
<title lang="en">XQuery Kick Start</title>
<author>James McGovern</author>
<author>Per Bothner</author>
<author>Kurt Cagle</author>
<year>2003</year>
<price>49.99</price>
</book>
</bookstore>';
EXEC sp_xml_preparedocument @int OUTPUT, @var
SELECT
*
into MyTable
FROM
OPENXML(@int, 'bookstore/book', 11)
with
(
category varchar(100),
title varchar(100),
author varchar(100)
author1 varchar(100),
author2 varchar(100)
);