子表结果连接

时间:2012-07-10 14:46:13

标签: sql sql-server sql-server-2008 tsql parent-child

我有一个父/子表,如下所示,在EmailQueueAttachments表上有一对多的关系。

ERD

父表(EmailQueue)在子表(EmailQueueAttachments)中有一行和两个相关行,在编写简单连接查询后,我得到以下结果。

SELECT     EmailQueue.ID, EmailQueue.SenderAddress, EmailQueue.RecipientList, EmailQueue.CCList, EmailQueue.Subject, EmailQueue.Body, EmailQueue.BodyHTML, 
                      EmailQueue.DisclaimerFooter, EmailQueue.Sent, EmailQueue.SendError, EmailQueue.CreatedDate,EmailQueueAttachments.AttachmentPath
FROM         EmailQueue LEFT OUTER JOIN
                      EmailQueueAttachments ON EmailQueue.ID = EmailQueueAttachments.EmailQueueID
WHERE     (EmailQueue.Sent = 0) AND (EmailQueue.SendError = 0) AND (EmailQueue.BodyHTML IS NULL)

4   xxxxxxx xxxxxxx xxxxxxx xxxxxxx xxxxxxx NULL    xxxxxxx 0   0   10/07/2012 11:58    \\server\orange.png
4   xxxxxxx xxxxxxx xxxxxxx xxxxxxx xxxxxxx NULL    xxxxxxx 0   0   10/07/2012 11:58    \\server\pear.png

是否有一种简单的方法可以将子表中的AttachmentPath列作为csv返回一行,还是需要编写存储过程并使用临时表来实现此目的?

1 个答案:

答案 0 :(得分:2)

这应该为您提供一列中的路径作为逗号分隔列表。

N.B。我没有测试,所以可能存在拼写错误。

SELECT  EmailQueue.ID, EmailQueue.SenderAddress, EmailQueue.RecipientList,
        EmailQueue.CCList, EmailQueue.Subject, EmailQueue.Body, EmailQueue.BodyHTML,
        EmailQueue.DisclaimerFooter, EmailQueue.Sent, EmailQueue.SendError, 
        EmailQueue.CreatedDate,
        substring((SELECT ( ', ' + EQA.AttachmentPath)
                           FROM EmailQueueAttachments EQA
                           WHERE EmailQueue.ID = EQA.EmailQueueID
                           FOR XML PATH( '' )
                          ), 3, 1000 ) as [Path List]
FROM EmailQueue 
WHERE   
     (EmailQueue.Sent = 0) AND (EmailQueue.SendError = 0) AND (EmailQueue.BodyHTML IS NULL)