From the database, I'm trying to generate an XML that looks like the following, for each row in the query result:
<Message>
<Header>
<MessageName>MyMessage</MessageName>
<TimeStamp>2017-03-31T14:32:48</TimeStamp>
<TrackingNum>1</TrackingNum>
</Header>
<Body>
<Activity>
<GUID>SomeGUID</GUID>
<OrderNum>3242432<OrderNum/>
<OrderDate>20160331143248</OrderDate>
</Activity>
</Body>
</Message>
The query I have looks like this:
SELECT
(SELECT DISTINCT top 20
[GUID],
OrderNum,
OrderDate,
FROM TableA
For XML PATH('Activity'), Type
) as Body
For XML path('Message'), TYPE
This query outputs all rows enclosed within <Message><Body>
tag, just one cell with the XML of everything. I don't know where to include the info for the <Header>
part.
The query above produces the following, which is incorrect/incomplete:
<Message>
<Body>
<Activity>
<GUID>sdlksdkljsdkl</GUID>
<OrderNum>23423423</OrderNum>
<OrderDate>20160431143248</OrderDate>
</Activity>
<Activity>
<GUID>sdfsdfsw4erw</GUID>
<OrderNum>45560900</OrderNum>
<OrderDate>20160531143248</OrderDate>
</Activity>
<Activity>
<GUID>retertertwew</GUID>
<OrderNum>873409384</OrderNum>
<OrderDate>20160631143248</OrderDate>
</Activity>
</Body>
</Message>
How do we get the Header Part appended before the <Body>
tag, while splitting the output into multiple rows? Thank you for any help.
EDIT:
Mock data for the Body/Activity
element :
GUID OrderNum OrderDate
AAAA 1000 2017-04-13 12:00
BBBB 2000 2017-04-13 12:00
CCCC 3000 2017-04-13 12:00
I'm trying to get each row in their own xml as in the first XML block above.
Just add the Header as an XML-typed column:
The result
Hints
20160531143248
. You should use ISO8601 within XML always. Otherwise you will get extra pain, when you try to read this.TOP
without anORDER BY
is - uhm - at least dangerous... (you see, that the order in my result is not the expected order?)UPDATE
According to your comments I think you are searching for one of these (test them with my mock-up table from above):