【问题标题】:SQL Query for XML nesting/groupingXML 嵌套/分组的 SQL 查询
【发布时间】:2018-08-01 16:41:52
【问题描述】:

我需要生成如下 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。我需要将所有公寓放入节点建筑 - >公寓。有任何想法吗?

【问题讨论】:

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


    【解决方案1】:

    在 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>
    

    【讨论】:

    • 感谢您的回答。它帮助了我
    【解决方案2】:

    您还需要为嵌套的 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')
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2018-05-16
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多