此触发器适用于一行,如何使其在多行上工作?

时间:2013-10-13 10:45:48

标签: sql-server tsql triggers

/* This trigger works for one row, how to make it work on multiple rows ?*/

CREATE TRIGGER SendMail ON contract
AFTER INSERT, UPDATE, DELETE 
AS

SET NOCOUNT ON
IF ( UPDATE(Contract_Status))
Begin

/* This comparison works for one row, how to make it work on multiple rows ?*/

IF ((SELECT Contract_Status FROM INSERTED) <> (select Contract_Status FROM DELETED))
Begin 


DECLARE @body NVARCHAR(MAX) = N'';
SELECT @body += CHAR(13) + CHAR(10) + RTRIM(Contract_Ref_1) FROM inserted;


  EXEC msdb.dbo.sp_send_dbmail
    @profile_name = 'AdminProfile',
    @recipients = 'XXXXX@live.be',
    @body = @body,
    @subject = 'Status Update BELUX_OEM';

End
End

1 个答案:

答案 0 :(得分:1)

我就是这样做的:

CREATE TRIGGER SendMail ON contract
AFTER INSERT, UPDATE, DELETE 
AS

SET NOCOUNT ON
IF ( UPDATE(Contract_Status))
Begin

    IF EXISTS(SELECT *
              FROM   INSERTED i
              JOIN   DELETED d ON i.PrimaryKey = d.PrimaryKey
              WHERE  d.Contract_Status <> i.Contract_Status)
    Begin 


    DECLARE @body NVARCHAR(MAX) = N'';
    SELECT @body += CHAR(13) + CHAR(10) + RTRIM(Contract_Ref_1) 
    FROM inserted i
    WHERE NOT EXISTS(SELECT * FROM deleted d
                     WHERE  i.PrimaryKey = d.PrimaryKey
                       AND  i.Constract_Status <> d.Contract_Status)

      EXEC msdb.dbo.sp_send_dbmail
        @profile_name = 'AdminProfile',
        @recipients = 'XXXXX@live.be',
        @body = @body,
        @subject = 'Status Update BELUX_OEM';

    End
End