sql-serverdatabasetriggersinsertafter

SQLServer after Insert trigger, does it loop through whole table or just inserted rows.?


I was wondering. I have this Trigger that does exactly what I want it to do.

      USE [IGOR]
      GO
      /****** Object:  Trigger [dbo].[AfterInsertTarget]    Script Date: 11/20/2013 14:46:06 ******/
      SET ANSI_NULLS ON
      GO
      SET QUOTED_IDENTIFIER ON
      GO


      ALTER TRIGGER [dbo].[AfterInsertTarget] ON  [dbo].[DMM_TARGET] 

      after insert 
      as 
      set nocount on 

      update DMM_TARGET 
      set ID_WEEK = 0 
      WHERE FREQ = 'Daily'    

My question is: Does the update statement do it's job of setting ID_WEEK to 0 if FREQ = 'Daily' only on the inserted rows? Or does it loop trough the whole table? because right now it's only 50000 entries. But If it gets like to millions, it's gonna take a while to insert a row only because of the Trigger.


Solution

  • Your trigger currently updates all rows, because there is no correlation to the inserted pseudo-table, which contains only the records involved with the trigger invocation. To affect only the new rows:

    ALTER TRIGGER [dbo].[AfterInsertTarget] 
    ON [dbo].[DMM_TARGET] 
    AFTER INSERT
    AS
    BEGIN
      SET NOCOUNT ON;
    
      UPDATE t SET ID_WEEK = 0
        FROM dbo.DMM_TARGET AS t
        WHERE EXISTS (SELECT 1 FROM inserted WHERE key = t.key);
    END
    GO
    

    Or:

    ALTER TRIGGER [dbo].[AfterInsertTarget] 
    ON [dbo].[DMM_TARGET] 
    AFTER INSERT
    AS
    BEGIN
      SET NOCOUNT ON;
    
      UPDATE t SET ID_WEEK = 0
        FROM dbo.DMM_TARGET AS t
        INNER JOIN inserted AS i
        ON t.key = t.key;
    END
    GO
    

    However it will be much easier to just create a default constraint on the ID_WEEK column.