因为要求是将多行传递到电子邮件的正文,所以最好以表格格式提供。
这可以通过在电子邮件正文中包含符合标准的达析报告的 HTML 表格来实现。
只需将列名替换为表 bo 中的正确名称即可。
让我们单独分解元素:
CREATE PROCEDURE dbo.DossierEmailSend
AS
为符合条件的达析报告创建一个保留表
DECLARE @dossiers TABLE (col1 varchar(100), col2 varchar(100), col3 varchar(100), col4 varchar(100));
插入符合条件的达析报告
INSERT INTO @dossiers
SELECT col1, col2, col3, convert(varchar,col4) col4
FROM bo
WHERE nmdos LIKE '%preço%'
AND datafinal = DATEADD(day, -1, CONVERT(date, GETDATE()))
创建行检查以确定是否发送电子邮件
DECLARE @rows int;
SET @rows = (SELECT COUNT(*) FROM @dossiers)
检查是否有任何档案符合标准
IF @rows > 0
BEGIN
设置正文元素
DECLARE @message varchar(1000);
-- declare the xml data to pass to the HTML body
DECLARE @xml NVARCHAR(MAX);
-- body will hold the HTML formatted table in the email
DECLARE @body NVARCHAR(MAX);
创建将每行数据保存为 xml 的列
SET @xml = CAST(( SELECT col1 AS 'td','',col2 AS 'td','', col3 AS 'td','', col4 AS 'td'
FROM @dossiers
FOR XML PATH('tr'), ELEMENTS ) AS NVARCHAR(MAX))
设置正文的 HTML
SET @body ='<html><body><H3>Dossier Info</H3>
<table border = 1>
<tr>
<th> col1 </th> <th> col2 </th> <th> col3 </th> <th> col4 </th></tr>'
将所有内容拼接在一起,附加 HTML 表格
SET @body = @body + @xml +'</table></body></html>'
SET NOCOUNT ON
发送电子邮件并将数据表附加到正文
EXEC dbo.uspSendEmail 'Dossiers FOund', 'aaaaaaaa@aaaa', @body, NULL, 'CC EMAIL 1'
SET NOCOUNT OFF
END
完成的解决方案应如下所示:
CREATE PROCEDURE dbo.DossierEmailSend
AS
--Create a holding table for the dossiers that met the criteria
DECLARE @dossiers TABLE (col1 varchar(100), col2 varchar(100), col3 varchar(100), col4 varchar(100));
--Insert the dossiers that met the criteria
INSERT INTO @dossiers
SELECT col1, col2, col3, convert(varchar,col4) col4
FROM bo
WHERE nmdos LIKE '%preço%'
AND datafinal = DATEADD(day, -1, CONVERT(date, GETDATE()))
--Create a row check to determine whether to send the email or not
DECLARE @rows int;
SET @rows = (SELECT COUNT(*) FROM @dossiers)
--Check if any dossiers met the criteria
IF @rows > 0
BEGIN
--Set the body elements
DECLARE @message varchar(1000);
-- declare the xml data to pass to the HTML body
DECLARE @xml NVARCHAR(MAX);
-- body will hold the HTML formatted table in the email
DECLARE @body NVARCHAR(MAX);
--Create the columns that will hold each row of data as xml
SET @xml = CAST(( SELECT col1 AS 'td','',col2 AS 'td','', col3 AS 'td','', col4 AS 'td'
FROM @dossiers
FOR XML PATH('tr'), ELEMENTS ) AS NVARCHAR(MAX))
--Set the HTML for the body
SET @body ='<html><body><H3>Dossier Info</H3>
<table border = 1>
<tr>
<th> col1 </th> <th> col2 </th> <th> col3 </th> <th> col4 </th></tr>'
--Stitch everything together, appending the HTML table
SET @body = @body + @xml +'</table></body></html>'
SET NOCOUNT ON
--Send the email and append the data table to the body
EXEC dbo.uspSendEmail 'Dossiers FOund', 'aaaaaaaa@aaaa', @body, NULL, 'CC EMAIL 1'
SET NOCOUNT OFF
END