用于XML嵌套/分组的SQL查询

时间:2018-08-01 16:41:53

标签: sql sql-server xml for-xml-path

我需要生成一个XML片段,如下所示:

<buldings>
  <building>
    <id>126433</id>
    <flats>
      <flat>
        <flat_id>ПК-01-15-01-072</flat_id>
      </flat>
      <flat>
        <flat_id>ПК-01-17-01-082</flat_id>
      </flat>
    </flats>
  </building>
</buldings>

我正在编写此sql:

select la.tisa_idcorpusdomclick [id]
    ,(
        select a.tisa_code [flat/flat_id] 
         from tisa_Article a 
         where 
               a.tisa_LayoutId = la.tisa_LayoutId 
           and a.tisa_ArticleId = la.tisa_ArticleId
         for xml path('flats'), type
      )
from (
       select l.tisa_idcorpusdomclick
             ,l.tisa_LayoutId
             ,a.tisa_ArticleId
         from tisa_layout l left join 
              tisa_article a on a.tisa_LayoutId = l.tisa_LayoutId 
        where l.tisa_idcorpusdomclick is not null 
          and a.statuscode = 4 
          and a.tisa_ArticleTypeCode = 2) la
for xml path('building'), root('buldings')

那返回我不正确的xml。我需要将所有单元放入节点构建->单元。有任何想法吗?

2 个答案:

答案 0 :(得分:0)

您还需要为嵌套XML查询指定root。像这样:

-- test data
with 
buildings(building_id) as (select '126433')
,flats(flat_id, building_id) as (
    select N'ПК-01-15-01-072', '126433'
    union
    select N'ПК-01-17-01-082', '126433'
)

-- actual query
select 
    building_id [id]
    ,(  select flat_id
        from flats
        where building_id = buildings.building_id
        for xml path('flat'), root('flats'), type
    )
from buildings
for xml path('building'), root('buildings')

答案 1 :(得分:0)

在SSMS中尝试一下,看看它能否使您朝正确的方向前进。

DECLARE @building TABLE ( id VARCHAR(10) );
INSERT INTO @building ( id ) VALUES ( '126433' );

DECLARE @flats TABLE ( id VARCHAR(10), flat_id VARCHAR(50) );
INSERT INTO @flats ( id, flat_id ) VALUES ( '126433', 'NK-01-15-01-072' ), ( '126433', 'NK-01-17-01-082' );

SELECT
    bldg.id, flats.flats AS 'flats'
FROM @building bldg
CROSS APPLY (
    SELECT CAST( (
        SELECT flat.flat_id FROM @flats flat WHERE flat.id = bldg.id ORDER BY flat.flat_id FOR XML PATH( 'flat' )
    ) AS XML ) AS flats
) AS flats
ORDER BY bldg.id
FOR XML PATH( 'building' ), ROOT( 'buildings' );

返回

<buildings>
  <building>
    <id>126433</id>
    <flats>
      <flat>
        <flat_id>NK-01-15-01-072</flat_id>
      </flat>
      <flat>
        <flat_id>NK-01-17-01-082</flat_id>
      </flat>
    </flats>
  </building>
</buildings>