如何在触发器中正确使用sp_send_dbmail?

时间:2017-04-20 18:09:11

标签: tsql stored-procedures triggers

我在名为Project的表上创建了一个触发器,查询成功编译但是当我向表中插入数据时,我得到一个错误说明:

Msg 14636, Level 16, State 1, Procedure sp_send_dbmail, Line 112 [Batch Start Line 139]
No global profile is configured. Specify a profile name in the @profile_name parameter.

以及:

Msg 3930, Level 16, State 1, Procedure sp_send_dbmail, Line 64 [Batch Start Line 139]
The current transaction cannot be committed and cannot support operations that write to the log file. Roll back the transaction.

我对sp_send_dbmail程序并不完全熟悉,但我试图在触发触发器时将其发送到xxxxx@gmail.com。

--Create a Table to hold the project audit
CREATE TABLE [dbo].[ProjectAudit](
    projectId char(4) not null,
    projectName varchar(50) null, 
    fundedbudget decimal(16,2) null,
    firmFedID char(9) null,
    statusID varchar(25) null,
    projectTypeID char(4) null, 
    startDate date null,  
    projectedEndDate date null,
    projectManager char(8) null,
    dateTimeCreated smalldatetime null,
    operation varchar(50),
    userName varchar(50)
)
go

-- Project trigger
create TRIGGER trg_ProjectAudit
ON Project
After Insert,Delete,Update
AS
Begin
     declare @name varchar(50)
     declare @body varchar(100) 
     if exists(select projectId from inserted)
     BEGIN
         select @name = projectName
         from inserted
         set @name = @name + ' has been inputted into the project table.'

         INSERT INTO ProjectAudit 
         (projectId, projectName, fundedbudget, firmFedID, statusID, projectTypeID, 
         startDate, projectedEndDate, projectManager, operation, dateTimeCreated, userName)
         SELECT projectId, projectName, fundedbudget, firmFedID, statusID, projectTypeID, 
         startDate, projectedEndDate, projectManager, 'INSERT', getdate(), System_user
         FROM Inserted
         exec msdb.dbo.sp_send_dbmail @recipients = 'xxxxx@gmail.com', 
         @body = @name
     END

     if exists(select projectId from deleted)
     begin
        select @name = projectName
         from deleted
         set @name = @name + ' has been deleted from the project table.'

        INSERT INTO ProjectAudit 
         (projectId, projectName, fundedbudget, firmFedID, statusID, projectTypeID, 
         startDate, projectedEndDate, projectManager, operation, dateTimeCreated, userName)
         SELECT projectId, projectName, fundedbudget, firmFedID, statusID, projectTypeID, 
         startDate, projectedEndDate, projectManager, 'DELETE', getdate(), System_user
         FROM deleted
         exec msdb.dbo.sp_send_dbmail @recipients = 'xxxxx@gmail.com', 
         @body = @name  
     end



     --check if a column update
     if (update(projectid) or update(projectTypeID))
     begin
        print 'ProjectID or ProjectTypeID column was updated'
        exec msdb.dbo.sp_send_dbmail @recipients = 'xxx@gmail.com',
            @body = 'Data has been updated in the project table.'   
     end
End
GO

0 个答案:

没有答案