我们经常需要向所有应用程序用户发送有关各种通知的电子邮件。由于各种原因(垃圾邮件过滤器、策略限制等),我们需要限制一封电子邮件发送通知的用户数量。如果电子邮件数量增加超过给定数量,则需要发送另一封电子邮件。
DECLARE @emails varchar(max)
with EmailList AS
(
SELECT row_number() over(order by email) as Seq,
Email from ApplicationUser
)
select @emails = COALESCE(@emails + ';', ' ') + email from EmailList where seq between 1 and 99;
上面的 block 为我提供了列表,但它存在缺陷,即有人检查存在多少用户并手动选择后续组。
如何根据需要选择尽可能多的行,直到选择所有电子邮件行。
最佳答案
在 SQL 2017 中,您可以使用 string_agg()
:
select string_agg(email, ';')
from (select row_number() over(order by email) as seqnum, au.*
from ApplicationUser au
) au
group by (seqnum - 1) / 100;
在早期版本中,您需要使用 XML 来执行此操作:
with e as (
select (row_number() over(order by email) - 1) / 100 as grp,
au.*
from ApplicationUser au
)
select stuff( (select ';' + email
from e
where e.grp = g.grp
for xml path ('')
), 1, 1, ''
) as emails
from (select distinct grp from e) g
关于sql - 在组中构建分号分隔的电子邮件列表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50532571/