在主题电子邮件中发送行数

时间:2015-12-09 16:41:00

标签: sql-server sql-server-2008 sql-server-2012

我编写了发送电子邮件的SQL Server脚本。电子邮件代码非常通用,因为我们从运行的SQL Server作业向用户发送了电子邮件。我现在需要使用该代码向其他用户组发送电子邮件以及脚本中的行数。我不知道如何在电子邮件正文中发送总行数。

为了使事情更清楚,说我需要发送客户数量。因此

Declare @CustomerCount int
SET @CustomerCount =  (SELECT count(CustomerID) from CustomerTable)

因此我需要发送一封说

的电子邮件

"数据库中的总客户数为:1000"

以下是发送电子邮件的存储过程。

CREATE PROCEDURE [dbo].[sp_SQLCustomEmailProc]   
   @From varchar(100) ,  
   @To varchar(350) , /* 200 */  
   @Subject varchar(250)=" ", /* 100 */  
   @Body varchar(4000) = "Test Body"     
   AS  
   Declare @iMsg int  
   Declare @hr int  
   Declare @source varchar(255)  
   Declare @description varchar(500)  
   Declare @output varchar(1000)  

--************* Create the CDO.Message Object ************************  
   EXEC @hr = sp_OACreate 'CDO.Message', @iMsg OUT  

--***************Configuring the Message Object ******************  
-- This is to configure a remote SMTP server.  
-- http://msdn.microsoft.com/library/default.asp?url=/library/en-us/cdosys/html/_cdosys_schema_configuration_sendusing.asp  
   EXEC @hr = sp_OASetProperty @iMsg, 'Configuration.fields("http://schemas.microsoft.com/cdo/configuration/sendusing").Value','2'  
-- This is to configure the Server Name or IP address.   
-- Replace MailServerName by the name or IP of your SMTP Server.  
   EXEC @hr = sp_OASetProperty @iMsg, 'Configuration.fields("http://schemas.microsoft.com/cdo/configuration/smtpserver").Value', 'smtp.mycompany.com'   

-- Save the configurations to the message object.  
   EXEC @hr = sp_OAMethod @iMsg, 'Configuration.Fields.Update', null  

-- Set the e-mail parameters.  
   EXEC @hr = sp_OASetProperty @iMsg, 'To', @To  
   EXEC @hr = sp_OASetProperty @iMsg, 'From', @From  
   EXEC @hr = sp_OASetProperty @iMsg, 'Subject', @Subject  

-- If you are using HTML e-mail, use 'HTMLBody' instead of 'TextBody'.  
   EXEC @hr = sp_OASetProperty @iMsg, 'TextBody', @Body  
   EXEC @hr = sp_OAMethod @iMsg, 'Send', NULL  

-- Sample error handling.  
   IF @hr <>0   
     select @hr  
     BEGIN  
       EXEC @hr = sp_OAGetErrorInfo NULL, @source OUT, @description OUT  
       IF @hr = 0  
         BEGIN  
           SELECT @output = '  Source: ' + @source  
           PRINT  @output  
           SELECT @output = '  Description: ' + @description  
           PRINT  @output  
         END  
       ELSE  
         BEGIN  
           PRINT '  sp_OAGetErrorInfo failed.'  
           RETURN  
         END  
     END  

-- Do some error handling after each step if you need to.  
-- Clean up the objects created.  
   EXEC @hr = sp_OADestroy @iMsg  

   PRINT 'Mail has been sent!'  

1 个答案:

答案 0 :(得分:1)

您运行的是哪个版本的SQL?如果您有2008+并且设置了数据库邮件配置文件,请使用sp_send_dbmail:

{{1}}