我有这个非常奇怪的问题,花了我几个小时才发现。我的代码在测试期间完美地工作,定义了静态@Start
和@End
变量,但是在触发器中,这些变量被意外更新,原因是第一个代码块中的行,它将值插入{{ 1}}。
我怀疑这一定是因为我从触发器所在的同一个表中选择了值。但是,由于这只是@tbl
而不是select
,我从未预料到这种行为。
我需要完成以下任务:当任务更新时,我需要检查Chore的所有其他任务以查看它们是否已完成,如果是,则执行内部逻辑。
我非常感谢这里的一些见解。我已经被困在这几天了。 :(
update
如果问题不是很明显,您可以尝试以下代码进行测试。
CREATE TRIGGER ut_Task_Update_PC ON tblTasks
AFTER UPDATE
AS
--Global Vars
declare @Start int, @End int, @ChoreID int
set @ChoreID = (select ChoreID from inserted)
set @Start = (select PC from inserted) -- PC = PercentComplete
set @End = (select PC from deleted)
print('1A: Start = '+cast(@Start as varchar(12))+', End = '+cast(@End as varchar(12)))
--Logic
if (@Start=100) and (@End=100) begin
print('Do nothing: Case 1.')
end else if (@Start=100) and (@End<100) begin
print('Do nothing: Case 2.')
end else if (@Start>0) and (@End<100) begin
print('Do nothing: Case 3.')
end else begin
declare @tbl table (PC int)
print('2A: Start = '+cast(@Start as varchar(12))+', End = '+cast(@End as varchar(12)))
--PROBLEM HERE: inserting explicit value = ok; inserting from same table
-- referenced by trigger somehow triggers another update but only once.
--insert @tbl values (1)
insert @tbl select isnull(PC,0) as [PC] from tblTasks
where ChoreID = @ChoreID and IsCancelled = 0
print('2B: Start = '+cast(@Start as varchar(12))+', End = '+cast(@End as varchar(12)))
if not exists (select null from @tbl where PC = 0)
and (select count(*) from @tbl) > 0 begin --DESIRED CASE
--Never reached
end
end