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

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

    I found this reference:

    create trigger myTrigger
    on SomeTable
    for insert 
    as 
    if (select count(*) 
        from SomeTable, inserted 
        where IsNumeric(SomeField) = 1) <> 0
    /* Cancel the insert and print a message.*/
      begin
        rollback transaction 
        print "You can't do that!"  
      end  
    /* Otherwise, allow it. */
    else
      print "Added successfully."
    

    I haven't tested it, but logically it looks like it should dp what you're after...rather than deleting the inserted data, prevent the insertion completely, thus not requiring you to have to undo the insert. It should perform better and should therefore ultimately handle a higher load with more ease.

    Edit: Of course, there is the potential that if the insert happened inside of an otherwise valid transaction that the wole transaction could be rolled back so you would need to take that scenario into account and determine if the insertion of an invalid data row would constitute a completely invalid transaction...

提交回复
热议问题