简体   繁体   中英

Get specific XML Child node in SQL Server

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>

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)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM