当前位置: 代码迷 >> Sql Server >> 触发器错误处理
  详细解决方案

触发器错误处理

热度:5   发布时间:2016-04-27 14:41:30.0
触发器异常处理
我写了一个触发器,每当有数据插入A时触发,并将这数据插入B表。
如果插入B时出错,如何让你能正常的插入A表。我是这么写的
如何做异常处理?

SQL code
ALTER trigger [dbo].[backup_pending_job_20110120]on [dbo].[_pending_job]after insert asbegindeclare  @var sysname   select @var=ltrim(JobID) from inserted   insert dbo._pending_job_backup_20110119(JobID,SystemID,Owner,ParentOwner,JobName,URL,IssuedTime,JobType,ActionType,SyncToGMCCPortal,CreateTime,LastUpdate,GMCCPortalID,GMCCAppID)   select JobID,SystemID,Owner,ParentOwner,JobName,URL,IssuedTime,JobType,ActionType,SyncToGMCCPortal,CreateTime,LastUpdate,GMCCPortalID,GMCCAppID from _pending_job where JobID=@var   end


------解决方案--------------------
你这个触发器本身是有错的!

select @var=ltrim(JobID) from inserted

这里,@var只是一个变量,但后边查询出的JobID是一个结果集,两者不能添 = 。。。
------解决方案--------------------
SQL code
create trigger insert_In on In_Productafter insertasbegindeclare @code1 varchar(10)    --对inserted中的procode进行判断select @code1 = procode from insertedif @code1 not in (select procode from ProductStore)    --入库产品在库存表中不存在时    begin        insert into ProductStore select * from inserted    endelse    --入库产品在库存中存在时    begin        update ProductStore        set quantity = quantity + (select quantity from inserted where procode = @code1)    endendgo
------解决方案--------------------
探讨
引用:
SQL code

--不好意思,没看仔细!不知道你的异常是什么异常?做一个判断! if else



对,我就是想做一个判断如果执行的没错,就ok,如果触发器有问题时,我要将那条数据存下来,不然数据会丢失的。

------解决方案--------------------
另外:
如果插入B时出错,如何让你能正常的插入A表。

这个需求的描述本身就有问题,结果就是允许A表插入不一定要插入到B表,一般情况失去触发器的意义。

------解决方案--------------------
把最后的 from _pending_job 
改为 from inserted