从未见过的SQL SERVER触发器问题,死也想不明白(50)

  • 主题发起人 主题发起人 阿群
  • 开始时间 开始时间

阿群

Unregistered / Unconfirmed
GUEST, unregistred user!
各位高人:我的问题是这样的,我有二个表:A和B,在A表的触发器中需要写数据至B表中,B表也有二个触发器,在写入数据至B表之前要先判断B表中数据是否己存在,如存在则更新,不存在则插入,但就是这样一个判断的速度却慢得要死,我专门将此判断的SQL语句执行的时间放入一个临时表中,发现要近2W多毫秒,执行判断语句根本就没触发B表的触发器,应该不是受B表触发器的影响,但奇怪的是去掉B表二个触发器后,速度就正常了,真不知是何原因?难道查询有触发器的表速度会受影响吗?各路高人给予明示,不甚感激!
 
set @BDate=getdate() --下面这句速度很慢,但去掉WorkReg表的触发器则正常 if not exists(select iId from WorkReg where PlanId=@PlanId and tiId=@tiId and StepId=@StepId and StationId=@Station1 and iEmplId=@iEmp1 and StationGp=@StationGp1 and RegDate=@Date1 and TmpStepAssId=@TmpStepAssId) begin set @EDate=getdate() insert into aCost(StepNo,begindate,enddate,costm) values (5,@BDate,@EDate,datediff(ms,@BDate,@EDate)) set @BDate=@EDate --插入数据至WorkReg表 select @iId=IsNull(max(iId)+1,1) from WorkReg insert into WorkReg(iId, PlanId, tiId, OrganId, ProdId, StepId, StationId, StationGp,iEmplId, Num, RegDate,PlanProdId,EmpId, WorkPrice,QuoPercent,AllQuoPercent,WorkTime,TmpStepAssId,IsTempTask, StepName,TechOrderId,StationName,SemiName,WorkNum, PlanNo,OrganCode,SalaKind,IsReversePoint,cEmpCode,cEmplN, SpecCode,DetailCode,ProdCode,ProdName,Factor,AlreadyReverse) values(@iId,@PlanId,@tiId,@OrganId,@ProdId,@StepId,@Station1,@StationGp1, @iEmp1,@Num1,@Date1,@PlanProdId,@IID1,@WorkPrice,@QuoPercent1,@AQuoPcent1, @WorkTime,@TmpStepAssId,@IsTempTask,@StepName,@TechOrderId,@StationN1,@SemiName,@WorkNum, @PlanNo,@OrganCode,@SalaKind,@IsReversePoint,@cEmpCode1,@cEmplN1,@SpecCode, @DetailCode,@ProdCode,@DetailName,@Factor,@AlreadyReverse) end else update WorkReg set Num=@Num1,QuoPercent=@QuoPercent1,AllQuoPercent=@AQuoPcent1,Factor=@Factor where PlanId=@PlanId and tiId=@tiId and StepId=@StepId and StationId=@Station1 and iEmplId=@iEmp1 and StationGp=@StationGp1 and RegDate=@Date1 and TmpStepAssId=@TmpStepAssId 贴出来大家看下,实在想不明白啊!
 
if not exists(select iId from WorkReg where PlanId=@PlanId and tiId=@tiId and StepId=@StepId and StationId=@Station1 and iEmplId=@iEmp1 and StationGp=@StationGp1 and RegDate=@Date1 and TmpStepAssId=@TmpStepAssId) 这句改一下试试select @iId=iID from WorkReg where PlanId=@PlanId and tiId=@tiId and StepId=@StepId and StationId=@Station1 and iEmplId=@iEmp1 and StationGp=@StationGp1 and RegDate=@Date1 and TmpStepAssId=@TmpStepAssIdif @iID>0 另外,如果不是一定必要,尽可能不要用触发器,否则日志会增长很快
 
谢谢哦!问题解决了,问题还是出在B表的触发器里,但现在还想不明白的是在还未写数据至B表之前仅执行下面这句就会用时那么久? if not exists(select iId from WorkReg where PlanId=@PlanId and tiId=@tiId and StepId=@StepId and StationId=@Station1 and iEmplId=@iEmp1 and StationGp=@StationGp1 and RegDate=@Date1 and TmpStepAssId=@TmpStepAssId)
 
后退
顶部