2

I am trying to load XMl to different tables with logical keys in MS SQL Server. I am stuck as I am getting all child nodes in SQL.

<Books>
<Book>
    <Name>Book1</Name>
    <Author>abc</Author>
    <Stores>
        <Name>Amazon</Name>
    </Stores>
</Book>
<Book>
    <Name>Book2</Name>
    <Author>cde</Author>
    <Stores>
        <Name>Flipkart</Name>
    </Stores>
</Book>
</Books>

I want to get result as below.

BookId  Name   Author  StoreXML
1       Book1  abc     <Stores><Name>Amazon</Name></Stores>  
2       Book2  cde     <Stores><Name>Flipkart</Name></Stores>

1 Answer 1

4

Try it like this

DECLARE @xml XML=
N'<Books>
<Book>
    <Name>Book1</Name>
    <Author>abc</Author>
    <Stores>
        <Name>Amazon</Name>
    </Stores>
</Book>
<Book>
    <Name>Book2</Name>
    <Author>cde</Author>
    <Stores>
        <Name>Flipkart</Name>
    </Stores>
</Book>
</Books>';

SELECT ROW_NUMBER() OVER(ORDER BY(SELECT NULL)) AS BookId --there is no id in your XML...
      ,b.value('(Name/text())[1]','nvarchar(max)') AS BookName 
      ,b.value('(Author/text())[1]','nvarchar(max)') AS Author
      ,b.query('Stores') AS StoreXML 
FROM @xml.nodes('/Books/Book') AS A(b)
Sign up to request clarification or add additional context in comments.

1 Comment

Thanks, I was using @xml.query rather than b.query to get specific child node.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.