Click here to Skip to main content
15,887,928 members
Please Sign up or sign in to vote.
5.00/5 (1 vote)
I have problems on quering or better numerating all items from a specified table.
Here are my tables (Third normal form):

MailTable: Id, Created, Subject
AddressTable: Id, Name
SenderTable: MailTableId, AddressTableId
RecipientTable: MailTableId, AddressTableId, State

Now i want to make a query to numerate alle senders and recipients for one mail.

My query:

select m.Id, m.Created, m.Subject, sender.Name, recipient.Name
from MailTable as m
join SenderTable as s on s.MailTableId = m.Id
join AddressTable as sender on sender.Id = s.AddressTableId
join RecipientTable as r on s.MailTableId = m.Id
join AddressTable as recipient on recipient.Id = r.AddressTableId

The result:
1 | 2008-01-01 | Test | sender1@domain.tld | recipient1@domain.tld
1 | 2008-01-01 | Test | sender1@domain.tld | recipient2@domain.tld
2 | 2008-01-02 | Test | sender3@domain.tld | recipient3@domain.tld
etc.

My target:
1 | 2008-01-01 | Test | sender1@domain.tld | recipient1@domain.tld,recipient2@domain.tld
2 | 2008-01-02 | Test | sender3@domain.tld | recipient3@domain.tld

How do I achive this, whithout using time-consuming queries?
The bad way is to lookup for every mail all recipients, but this is not the best way!
Should I compare all records and extract my desired information?

Please Help me. Thanks!

modified on Tuesday, July 22, 2008 5:09 AM
Posted

1 solution

( You are using SQL2005, right? :) )

Try this:

<br />;WITH RecipientsByMail (MailId, RecipientList) AS (<br />    select mx.Id AS MailId , <br />        (   select AddressTable.Name+','<br />            from MailTable<br />            join RecipientTable on RecipientTable.MailTableId = MailTable.Id<br />            join AddressTable   on AddressTable.Id = RecipientTable.AddressTableId<br />            WHERE MailTable.Id = mx.Id<br />            FOR XML PATH('')<br />        ) AS RecipientList <br />    from MailTable as mx<br />)<br />select m.Id, m.Created, m.Subject, sender.Name, r.RecipientList<br />from MailTable as m<br />join SenderTable as s on s.MailTableId = m.Id<br />join AddressTable as sender on sender.Id = s.AddressTableId<br />join RecipientsByMail as r on r.MailId = m.Id ;


 
Share this answer
 


CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900