我遇到了这个非常奇怪的问题,我花了几个小时才发现。我的代码在定义了静态@Start
和@End
变量的测试期间运行良好,但在触发器中,这些都被意外更新,原因是第一个代码块中将值插入到@tbl
.
我怀疑这一定是因为我从触发器所在的同一个表中选择值。但是,由于这只是一个select
而不是一个,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
如果问题不是很明显,您可以尝试以下代码进行测试。
--Testing: use this sample table and add the above trigger
-- I trimmed away a LOT of extraneous code, but this should
-- reflect the same problems I'm having
CREATE TABLE tblTask(
TaskID int IDENTITY(1,1) NOT NULL,
ChoreID int NOT NULL,
PC int,
IsCancelled bit
)