SQL显式使用XML显式,从子/不同查询生成元素

时间:2011-01-07 22:55:08

标签: sql sql-server xml sql-server-2008 export-to-xml

我有一个帐户表和一个广告系列表,每个帐户都有一定数量的广告系列与之关联。不,我想将帐户ID和与该帐户ID相关联的所有广告系列ID导出到此结构中的XML

<Accounts>
            <Account>
                        <AccountID></AccountID>
                        <AccountName></AccountName>
                        <CampaignIDs>
                                    <CampaignID></CampaignID>
                                    <CampaignID></CampaignID>
                        </CampaignIDs>
            </Account>
</Accounts>

我使用XML Explicit来控制数据输出为XML,这是我到目前为止所获得的。

SELECT
    1 AS Tag,
    NULL AS Parent,
    NULL AS 'Accounts!1',
    NULL AS 'Account!2!AccountID!Element',
    NULL AS 'Account!2!AccountName!Element',
    NULL AS 'Account!2!FMID!Element'
    UNION ALL
 SELECT
 2 AS Tag,
 1 AS Parent, 
 NULL,
 a.id as AccountID,
 a.Name as AccountName,
 NULL
 from Account a
FOR XML EXPLICIT

现在我想执行另一个查询,例如Select id from campaign where accountid = var 然后将所有这些广告系列ID附加到xml结构中。

我该怎么做?

1 个答案:

答案 0 :(得分:4)

我建议使用FOR XML PATH代替FOR XML EXPLICIT - 它更容易使用,更具表现力。

见:

-- set up test data
declare @Accounts table (AccountID INT, AccountName VARCHAR(50))
declare @Campaigns table (CampaignID INT, AccountID INT, CampaignName varchar(50))

insert into @Accounts values(1, 'Account #1'),(2, 'Account #2')
insert into @Campaigns values(1, 1, 'Campaign #1-1'), (2, 1, 'Campaign #2-1'), (3, 1, 'Campaign #3-1'),
(4, 2, 'Campaign #1-2'), (5, 2, 'Campaign #2-2')

-- SELECT with FOR XML PATH and a nested SELECT/FOR XML PATH,TYPE    
select 
    AccountID,
    AccountName,
    (SELECT CampaignID  
     FROM @Campaigns c
     WHERE c.AccountID = a.AccountID
     FOR XML PATH(''),TYPE) AS 'CampaignIDs'
FROM 
    @Accounts a
FOR XML PATH('Account'),ROOT('Accounts')

这个SELECT语句给出了以下输出:

<Accounts>
  <Account>
    <AccountID>1</AccountID>
    <AccountName>Account #1</AccountName>
    <CampaignIDs>
      <CampaignID>1</CampaignID>
      <CampaignID>2</CampaignID>
      <CampaignID>3</CampaignID>
    </CampaignIDs>
  </Account>
  <Account>
    <AccountID>2</AccountID>
    <AccountName>Account #2</AccountName>
    <CampaignIDs>
      <CampaignID>4</CampaignID>
      <CampaignID>5</CampaignID>
    </CampaignIDs>
  </Account>
</Accounts>