I got stuck with an xml creation challenge.
My challenge is to generate an xml from a data table with below definition
Table marketingCampaign
id INT
campaign_code
campaign_start_date
activity_code
target_email_address
comms
This xml will be forwarded to a 3rd party application and expecting the following format, below.
<xml ....>
<marketCampaign type='C'>
<campaign>
<campaign_code/>
<campaign_start_date/>
<campaign>
</marketCampaign>
<marketCampaign type='A'>
<activity>
<activity_code/>
<campaign_code/>
<activity>
</marketCampaign>
<marketCampaign type='M'>
<message>
<activity_code/>
<target_email_address/>
<message>
</marketCampaign>
</xml>
I want to limit this using plain SQL scripts (if possible), so I have used the 'FOR XML PATH' functionality. I have tried different combination to achieve above formatting without writing multiple sql statement with no success. I have managed to generate below xml but the 3rd party apps rejected this formatting.
<xml ....>
<marketCampaign type='C'>
<campaign>
<campaign_code/>
<campaign_start_date/>
<activity>
<activity_code/>
<campaign_code/>
<message>
<activity_code/>
<target_email_address/>
<message>
</activity>
<campaign>
</marketCampaign>
</xml>
My question is it possible to accomplish the above xml format with a single SQL, what is the most efficient approach to achieve this?
I can write a lengthy script to generate the xml format as per the 3rd party requirements, however I am trying to avoid that option if possible.
UPDATE
Below is the current SQL I tried
SELECT DISTINCT
'C' AS "@resultsType",
c.campaign_code AS "campaign/campaign_code",
CONVERT(DATE, campaign_start_date, 102) AS "campaign/campaign_start_date",
CONVERT(DATE, GETDATE(), 102) AS "campaign/authorizeDate",
'A' AS "marketCampaign/@resultsType",
c.activity_code AS "activity/code",
c.campaign_code AS "activity/campaign_code",
'M' AS "marketCampaign/@resultsType",
c.activity_code AS "message/activityCode",
c.target_email_address AS "message/target_email_address",
c.comms AS "message/fileText"
FROM
dev.campaign.marketting_data c
FOR XML PATH('marketCampaign'), ROOT('xml')
The thing is I do not want to repeat "resultType=C" multiple times, unless its a new set of campaign_code
, same rules applies to the activity_code
.