小编典典

获取嵌套的XML输出sql server

sql

我在sql server数据库中的xml输出有问题。我的桌子:

CREATE TABLE [dbo].[test_table](
    [id] [int] IDENTITY(1,1) NOT NULL,
    [firstname] [nvarchar](255) NULL,
    [lastname] [nvarchar](255) NULL,
    [city] [nvarchar](255) NULL,
    [street] [nvarchar](255) NULL,
    [streetno] [int] NULL
)

我想要输出,其中Address嵌套在每个Person内,如下所示:

<Root>
  <Person id="1">
    <firstname>Stefanie</firstname>
    <lastname>Buckley</lastname>
    <Address>
      <city>Oklahoma</city>
      <street> Cowley Road</street>
      <streetno>34</streetno>
    </Address>
  </Person>
  <Person id="2">
    <firstname>Sandy</firstname>
    <lastname>Mc Gee</lastname>
    <Address>
      <city>Montgomery</city>
      <street> Hague Parkway</street>
      <streetno>27</streetno>
    </Address>
  </Person>
</Root>

我已经尝试过嵌套选择:

 select tbl1.id '@id', tbl1.firstname, tbl1.lastname,
 (
 select city,street,streetno from test_table as tbl2
 where tbl2.id = tbl1.id
 for xml path('Address')
 ) 
 from test_table as tbl1
 for xml path('Person'), Root('Root')

但是输出是这样的:

<Root>
  <Person id="1">
    <firstname>Stefanie</firstname>
    <lastname>Buckley</lastname>&lt;Address&gt;&lt;city&gt;Oklahoma&lt;/city&gt;&lt;street&gt; Cowley Road&lt;/street&gt;&lt;streetno&gt;34&lt;/streetno&gt;&lt;/Address&gt;</Person>
  <Person id="2">
    <firstname>Sandy</firstname>
    <lastname>Mc Gee</lastname>&lt;Address&gt;&lt;city&gt;Anchorage&lt;/city&gt;&lt;street&gt; North Green Clarendon Road&lt;/street&gt;&lt;streetno&gt;29&lt;/streetno&gt;&lt;/Address&gt;</Person>
  <Person id="3">

我做错了什么?


阅读 208

收藏
2021-04-19

共1个答案

小编典典

您忘记了, type,不需要从表中读取信息。

select tbl1.id '@id'
    , tbl1.firstname
    , tbl1.lastname
    , (
        select city
            , street
            , streetno
        for xml path('Address'), type
    ) 
from test_table as tbl1
for xml path('Person'), type, Root('Root')
2021-04-19