SQL Server “AFTER INSERT” trigger doesn't see the just-inserted row

后端 未结 12 1965
庸人自扰
庸人自扰 2020-12-23 14:05

Consider this trigger:

ALTER TRIGGER myTrigger 
   ON someTable 
   AFTER INSERT
AS BEGIN
  DELETE FROM someTable
         WHERE ISNUMERIC(someField) = 1
END         


        
12条回答
  •  独厮守ぢ
    2020-12-23 14:22

    You can reverse the logic. Instead of deleting an invalid row after it has been inserted, write an INSTEAD OF trigger to insert only if you verify the row is valid.

    CREATE TRIGGER mytrigger ON sometable
    INSTEAD OF INSERT
    AS BEGIN
      DECLARE @isnum TINYINT;
    
      SELECT @isnum = ISNUMERIC(somefield) FROM inserted;
    
      IF (@isnum = 1)
        INSERT INTO sometable SELECT * FROM inserted;
      ELSE
        RAISERROR('somefield must be numeric', 16, 1)
          WITH SETERROR;
    END
    

    If your application doesn't want to handle errors (as Joel says is the case in his app), then don't RAISERROR. Just make the trigger silently not do an insert that isn't valid.

    I ran this on SQL Server Express 2005 and it works. Note that INSTEAD OF triggers do not cause recursion if you insert into the same table for which the trigger is defined.

提交回复
热议问题