[英]Getting error “The rollback transaction request has no corresponding begin transaction”
I am trying to create a trigger and for some reason the second if statement breaks my code. 我试图创建一个触发器,由于某种原因,第二个if语句破坏了我的代码。
If I delete the second if statement the code will work. 如果我删除第二个if语句,代码将起作用。 The error that I am getting is:
我得到的错误是:
The rollback transaction request has no corresponding begin transaction
回滚事务请求没有相应的开始事务
My code: 我的代码:
create trigger insertemployee
on jobinsailing
after insert
as
BEGIN TRANSACTION
declare @sailingID int,
@employeeID char(9),
@jobTitle varchar(10),
@sailingStartDate date,
@sailingEndDate date
select @sailingId = inserted.sailingid,
@employeeID = inserted.employeeid,
@jobTitle = inserted.jobtitle,
@sailingStartDate = sailing.leavingtime,
@sailingEndDate = sailing.returntime
from inserted
inner join sailing
on inserted.sailingid = sailing.sailingid
if exists(select employeeid
from sailing
inner join jobinsailing
on sailing.sailingid = jobinsailing.sailingid
where ( @sailingStartDate <= returntime )
and ( leavingtime <= @sailingEndDate )
and employeeid = @employeeID) rollback TRANSACTION;
else if exists((select sailing.sailingid
from sailing
inner join jobinsailing
on jobinsailing.sailingid = sailing.sailingid
where Datediff(day, @sailingStartDate, sailing.leavingtime) <= 4
or Datediff(day, @sailingEndDate,sailing.leavingtime) <= 4
or Datediff(day, @sailingStartDate,sailing.returntime) <= 4
or Datediff(day, @sailingEndDate,sailing.returntime) <= 4
)) rollback TRANSACTION;
COMMIT TRANSACTION
What you are trying to achieve is to conditionally insert records into a table using a trigger. 您要实现的是使用触发器有条件地将记录插入表中。
This is generally a bad approach. 这通常是一种糟糕的方法。 Your code (Stored Procedures and/or business tier code) should determine if the record should be inserted first before inserting it.
您的代码(存储过程和/或业务层代码)应确定是否应在插入记录之前插入记录。 Triggers are not the best tool for this - they are meant to allow you to enforce complex constraints.
触发器不是最好的工具 - 它们旨在允许您强制执行复杂的约束。
Assuming that you must use triggers, then I suggest you use INSTEAD OF
triggers. 假设您必须使用触发器,那么我建议您使用
INSTEAD OF
触发器。 They are designed to override the default insert process that normally occurs and allow you to insert (or not insert) data, rather than having to rollback transactions. 它们旨在覆盖通常发生的默认插入过程,并允许您插入(或不插入)数据,而不必回滚事务。
As @DaleBurrell has pointed out, trigger is executed once per insert operation and inserted
table can contain multiple rows. 正如@DaleBurrell指出的那样,每次插入操作都会执行一次触发器,并且
inserted
表可以包含多行。 It is best practice to code your triggers such that they allow multi row operations but you can also enforce single row operations by adding this line to the top of your trigger IF (ROWCOUNT_BIG() > 1) ROLLBACK
. 最佳做法是对触发器进行编码,使它们允许多行操作,但您也可以通过将此行添加到触发器
IF (ROWCOUNT_BIG() > 1) ROLLBACK
的顶部来强制执行单行操作。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.