I have the following table rows in MyTable:
MessageID EMailAddress DisplayName RecipientType
1 joe@email.com Joe To
1, Bob@email.com Max From
1, Max@email.com NULL To
1, Secret@email.com Secret Bcc
I am trying to convert this to XML that looks like the following:
<to>
<displayName>Joe</displayName>
<address>joe@email.com</address>
</to>
<from>
<displayName>Bob</displayName>
<address>Bob@email.com</address>
</from>
<to>
<address>Max@email.com</address>
</to>
<bcc>
<displayName>Secret</displayName>
<address>Secret@email.com</address>
</bcc>
I am close but cannot figure out how to convert the RecipientType to the parent element for the other two columns
SELECT
a.EmailAddress as address,
a.DisplayName as displayName
FROM MyTable a
WHERE a.Id = 1
FOR XML PATH('address'), TYPE
Is there a way to make the "FOR XML PATH('address')" be the RecipientType instead of a hard coded 'address'? Or is there another alternative?
I had also tried playing around with PIVOT but it didn't seem to help.
I know I could use dynamic SQL but I am trying to stay away from that.