使用For XML嵌套子元素

时间:2015-11-04 00:13:14

标签: sql sql-server

我的示例数据和表架构如下所示

CREATE TABLE [cs].[binary_fees](
    [deal_id] [int] NULL,
    [fee_name] [varchar](255) NULL,
    [fee_type] [varchar](255) NULL,
    [fee_value] [float] NULL
) ON [PRIMARY]

deal_id     fee_name                fee_type        fee_value
82049956    Servicer Fees           Total Pool      50
82049956    Trustee Fees            Fixed Amount    0

823531463   Mgmt-Co-Fee             Fixed Amount    51000
823531463   Custodian Fees          Fixed Amount    5000

我正在尝试编写一个sql查询来获取以下xml输出:

<Fees>
  <Fee dealId="82049956">
    <FeeOverride fee_name="Servicer Fees" fee_type="Total Pool" fee_value="5.000000000000000e+001" />
    <FeeOverride fee_name="Trustee Fees" fee_type="Fixed Amount" fee_value="0.000000000000000e+000" />

  </Fee>
  <Fee dealId="823531463">
    <FeeOverride fee_name="Mgmt-Co-Fee" fee_type="Fixed Amount" fee_value="5.100000000000000e+004" />
    <FeeOverride fee_name="Custodian Fees" fee_type="Fixed Amount" fee_value="5.000000000000000e+003" />

  </Fee>
</Fees>

我编写了一个可行的示例查询,但缺点是xml属性是由我想避免的列名定义的。

(SELECT Fee.dealId, FeeOverride.fee_name,
                         FeeOverride.fee_type, FeeOverride.fee_value
                         FROM #dealIdList AS Fee
                         INNER JOIN cs.binary_fees AS FeeOverride
                         ON FeeOverride.deal_id = Fee.dealId
                         FOR XML AUTO, ROOT ('Fees'))

有没有更好的方法在sql server中获取相同的xml输出?

由于

1 个答案:

答案 0 :(得分:0)

使用FOR XML EXPLICIT:

select distinct Tag = 1, Parent = 0, 
            [Fees!1!deal_id] = id.deal_id, 
            [FeeOverride!2!fee_name] = null, [FeeOverride!2!fee_type] = null, [FeeOverride!2!fee_value] = null
    from #dealIdList id
union all 
select Tag = 2, Parent = 1, 
            [Fees!1!deal_id] = bf.deal_id, 
            [FeeOverride!2!fee_name] = bf.fee_name,
            [FeeOverride!2!fee_type] = bf.fee_type,
            [FeeOverride!2!fee_value] = bf.fee_value
    from #dealIdList id
        join binary_fees bf on bf.deal_id = id.deal_id
order by 3, 1
for XML EXPLICIT, ROOT('Fee')

我使用了以下表格和数据

CREATE TABLE [binary_fees](
    [deal_id] [int] NULL,
    [fee_name] [varchar](255) NULL,
    [fee_type] [varchar](255) NULL,
    [fee_value] [float] NULL
) ON [PRIMARY]
insert into binary_fees values('82049956',' Servicer Fees','Total Pool',' 50'),
('82049956','Trustee Fees','Fixed Amount',' 0'),
('823531463','Mgmt-Co-Fee','Fixed Amount',' 51000'),
('823531463','Custodian Fees','Fixed Amount',' 5000')
create table #dealIdList ([deal_id] [int] NULL)
Insert into #dealIdList select distinct deal_id from binary_fees