我试图用ms sql server中的逻辑键将xml加载到不同的表中。
在获取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>

我想得到如下结果。
BookId  Name   Author  StoreXML
1       Book1  abc     <Stores><Name>Amazon</Name></Stores>
2       Book2  cde     <Stores><Name>Flipkart</Name></Stores>

最佳答案

像这样试试

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)

关于sql - 在SQL Server中获取特定的XML子节点,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/41141457/

10-09 18:56