How to abort an insert of multiple rows in a trigger

允我心安 提交于 2019-12-22 08:49:55

问题


With sql Server 2005. I have declared a trigger that get fired "AFTER INSERT, UPDATE" , in this trigger I'm using a WHILE and a CURSOR to loop on the INSERTED table's rows. When I find a row that does not sotisfy a specific condition:

I want the trigger to rise an error and do not insert any of the rows that fired the trigger (not even those that already satisfaied my condition). <--- I don't know how to do this!

Can you tell me how can I rise the error and prevent the insertion?


回答1:


use rollback

IF <some condition>
BEGIN
   RAISERROR ('condition doesn't satisfy something', 16, 1)
   ROLLBACK TRANSACTION
END



回答2:


I'm not sure what logic you are doing in that cursor loop, but if at all possible try to replace the cursor loop with a query:

if exists (select PK from INSERTED where .....)
BEGIN
    --from @SQLMenace's answer
    RAISERROR ('condition doesn't satisfy something', 16, 1)
    ROLLBACK TRANSACTION

END

a cursor in a trigger gives me a bad feeling: locking, blocking, and slow come to mind...



来源:https://stackoverflow.com/questions/794064/how-to-abort-an-insert-of-multiple-rows-in-a-trigger

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!