2

我有一个父/子表,如下所示,在 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 返回一行,还是我需要编写一个存储过程并使用临时表来实现这一点?

4

1 回答 1

3

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

注意我没有测试所以可能有错别字。

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)
于 2012-07-10T14:49:00.147 回答