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

后端 未结 12 1987
庸人自扰
庸人自扰 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:19

    UPDATE: DELETE from a trigger works on both MSSql 7 and MSSql 2008.

    I'm no relational guru, nor a SQL standards wonk. However - contrary to the accepted answer - MSSQL deals just fine with both recursive and nested trigger evaluation. I don't know about other RDBMSs.

    The relevant options are 'recursive triggers' and 'nested triggers'. Nested triggers are limited to 32 levels, and default to 1. Recursive triggers are off by default, and there's no talk of a limit - but frankly, I've never turned them on, so I don't know what happens with the inevitable stack overflow. I suspect MSSQL would just kill your spid (or there is a recursive limit).

    Of course, that just shows that the accepted answer has the wrong reason, not that it's incorrect. However, prior to INSTEAD OF triggers, I recall writing ON INSERT triggers that would merrily UPDATE the just inserted rows. This all worked fine, and as expected.

    A quick test of DELETEing the just inserted row also works:

     CREATE TABLE Test ( Id int IDENTITY(1,1), Column1 varchar(10) )
     GO
    
     CREATE TRIGGER trTest ON Test 
     FOR INSERT 
     AS
        SET NOCOUNT ON
        DELETE FROM Test WHERE Column1 = 'ABCDEF'
     GO
    
     INSERT INTO Test (Column1) VALUES ('ABCDEF')
     --SCOPE_IDENTITY() should be the same, but doesn't exist in SQL 7
     PRINT @@IDENTITY --Will print 1. Run it again, and it'll print 2, 3, etc.
     GO
    
     SELECT * FROM Test --No rows
     GO
    

    You have something else going on here.

提交回复
热议问题