将select列输出转换为sp_send_dbmail的以分号分隔的列表

时间:2011-12-06 12:58:28

标签: sql sql-server stored-procedures

我有一个复杂的select语句(几个查询的并集),它输出一个列,例如

| email            |
| test@domain.com  |
| test2@domain.com |
| test3@domain.com |

我想将它提供给sp_send_dbmail的@blind_copy_recipients,它需要一个分号(;)分隔列表。

通常会使用COALESCE和变量来完成此操作,但是使用UNIONS语句似乎无法做到这一点。

有一种简单的方法吗?

虽然输入这个问题已经发生在我身上,但更好的办法可能是使用光标循环记录并单独发送消息,但我仍然对答案感兴趣......

6 个答案:

答案 0 :(得分:1)

您可以使用两种方法完成此操作:

  1. 将联合结果放在临时表中。
  2. 使用COALESCE。
    1. 使用结果union作为子查询。
    2. 使用COALESCE。

答案 1 :(得分:1)

将选区粘在CTE上?

declare @addr varchar(1024) = ''
;with T(addr) as (
    select email from emails where id = 1
    union
    select email from moreemails where id = 1
    ...
)
select @addr += case @addr when '' then '' else ';' end + addr from T

答案 2 :(得分:1)

尽可能避免使用游标。

与此同时,试试这个:

DECLARE @blind_copy_recipients VARCHAR(4000) 
-- Or whatever is the suitable size you expect

SELECT @blind_copy_recipients = COALESCE(@blind_copy_recipients + ', ', '') + 
   CAST(BCC.BLIND_COPY_RECIPIENTS_UNION_OUTPUT_COLUMN AS VARCHAR(50)) 
    -- Again, change to suit your needs
FROM 
(
-- SELECT UNION SELECT UNION SELECT UNION --
) AS BCC

SELECT @blind_copy_recipients

答案 3 :(得分:0)

在T-SQL中,您可以像这样使用COALESCE

declare @result nvarchar (max)
set @result = ''

select @result = coalesce (
                   case when @result = ''
                   then YourColumnName
                   else @result + ',' + YourColumnName
                   end
                 ,'')
from dbo.YourTableName

print @result

答案 4 :(得分:0)

They are severalt methods to achieve this。 “黑盒子XML方法”就是其中之一,这里是一个模板:

SELECT p1.CategoryId,
          ( SELECT ProductName + ',' 
              FROM Northwind.dbo.Products p2
             WHERE p2.CategoryId = p1.CategoryId
             ORDER BY ProductName
               FOR XML PATH('') ) AS Products
      FROM Northwind.dbo.Products p1
     GROUP BY CategoryId ;

对于您的架构

SELECT email + ',' 
  FROM yourComplexQuery p2
   FOR XML PATH('') ;

这是一个示例:http://data.stackexchange.com/stackoverflow/q/120618/

答案 5 :(得分:-1)

您可以将Union结果存储在临时表中。

相关问题