1

我有一个帐户表和一个活动表,每个帐户都有一定数量的活动与之关联。不,我想在此结构中将帐户 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 结构中。

我该怎么做?

4

1 回答 1

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>
于 2011-01-08T10:21:10.320 回答