子查询返回的值不止一个。当子查询跟随在 =、!=、<、<=、>、>= 之后,或子查询用作表达式时,这种情况是不允许的。...

本文介绍了一种解决SQL触发器在多条记录更新时出现的问题的方法。通过使用IF EXISTS和IN操作符来确保更新操作正确执行。

  刚开始仿照前辈的触发器,写了一个这样的触发器:

 

代码
--更新合同的 【提交时间】
declare@IDint
declare@useridint
declare@statusnchar(40)

select@ID= (select acon_acontractid from inserted)
select@userid= (select i.acon_userid from inserted i,deleted d where i.ACon_AContractID=d.ACon_AContractID and (i.acon_userid<>d.acon_userid or i.acon_userid isnotnulland d.acon_userid isnull))
select@status= (select i.acon_status from inserted i,deleted d where i.ACon_AContractID=d.ACon_AContractID and (i.acon_status<>d.acon_status or i.acon_status isnotnulland d.acon_status isnull))

--当插入的数据的是当前处理人或者是状态时
if(@useridisnotnullor@statusisnotnull)
begin
update acontract set acon_submittime =getdate() where acon_acontractid=@ID
end

 

这样写触发器。有个问题,update数据的时候,如果是多条记录一起更新的话,那么   select acon_acontractid from inserted 返回的是一个数据集。

就会报错,错误如标题。

 

修正:

判断的时候尽量采用  if exists 或者 if upate() 之类的语法。

在执行操作的时候就使用  【in】操作符,就id可以 等于一个结果集了。

修改如下:

 

代码
ifupdate (acon_userid)
begin
update acontract set acon_submittime =getdate() where acon_acontractid in (select acon_acontractid from inserted)
end

ifupdate (acon_status)
begin
update acontract set acon_submittime =getdate() where acon_acontractid in (select acon_acontractid from inserted)
end

测试ok。

 

 

转载于:https://www.cnblogs.com/novus/archive/2010/02/08/1666060.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值