SQL Server Trigger IF ( UPDATE (STATUS) IN?

mlmc2os5  于 2023-10-15  发布在  其他
关注(0)|答案(2)|浏览(114)

I have an UPDATE trigger on the column STATUS. This column takes int. Instead of firing on every change, I want it to fire only when STATUS changes to 3, 4 or 6.

How can I achieve this? I'm guessing I have to extend this rule?

IF ( UPDATE (STATUS) )
USE [TEST]
GO
/****** Object:  Trigger [dbo].[PROJECT_StatusUpdate]    Script Date: 27-9-2023 16:47:33 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
ALTER TRIGGER [dbo].[PROJECT_StatusUpdate] ON [dbo].[PROJECT]
AFTER UPDATE
AS

IF ( UPDATE (STATUS) )

BEGIN
SET NOCOUNT ON;

INSERT [IT].[dbo].[ProjectStatusLog]
  (ProjectNO, OldStatus, NewStatus, DateChanged)
SELECT
  d.PROJECTNO,
  d.STATUS,
  i.STATUS,
  GETDATE()
FROM inserted i
FULL JOIN deleted d ON d.OBJECTID = i.OBJECTID
END;
h79rfbju

h79rfbju1#

You don't need to use FULL JOIN , INNER JOIN is fine. Place the required checking condition in the WHERE clause

IF ( UPDATE (STATUS) )
  BEGIN
      INSERT [IT].[dbo].[ProjectStatusLog] 
             (ProjectNO, OldStatus, NewStatus, DateChanged)
      SELECT ProjectNO   = d.PROJECTNO,
             OldStatus   = d.STATUS,
             NewStatus   = i.STATUS,
             DateChanged = GETDATE()
      FROM   inserted i 
             INNER JOIN deleted d ON d.ProjectNO = i.ProjectNO
      WHERE  i.STATUS <> d.STATUS     -- when there is a change in STATUS value
      AND    i.STATUS IN (3, 4, 6);   -- and new value is 3, 4 or 6
  END;
bgibtngc

bgibtngc2#

Thanks for the help. Got it working.

BEGIN
SET NOCOUNT ON;

      INSERT [IT].[dbo].[ProjectStatusLog] 
             (ProjectNO, OldStatus, NewStatus, DateChanged)
      SELECT ProjectNO   = d.PROJECTNO,
             OldStatus   = d.STATUS,
             NewStatus   = i.STATUS,
             DateChanged = GETDATE()
      FROM   inserted i 
             INNER JOIN deleted d ON d.OBJECTID = i.OBJECTID
      WHERE  i.STATUS <> d.STATUS     -- when there is a change in STATUS value
      AND    ((i.STATUS NOT IN (4, 6)) AND (d.STATUS IN (4, 6)));   -- and new value is not 4, 6, old value is 4, 6 (annulering, teruggestuurd)
END;

相关问题