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

--更新合同的 【提交时间】
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
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
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。