我正在使用sql-server 2012,我写了一个这样的触发器:
ALTER TRIGGER [dbo].[ModValue]
ON [dbo].[Table1]
AFTER UPDATE
AS
BEGIN
SET NOCOUNT ON;
declare @ocid bigint
declare @ncid bigint,@pid bigint
set @ocid=(select CategoryId from deleted)
select @ncid=CategoryId,@pid=Id from inserted
if(@ocid<>@ncid)
begin
delete from [Table2] where ProductId=@pid
delete from [Table3] where ProductId=@pid
delete from [Table4] where ProductId=@pid
end
END
当我想更新我的表(Table1)时,我收到了这个错误:
Msg 512,Level 16,State 1,Procedure ModValue,Line 15
子查询返回的值超过1。子查询时不允许这样做 follow =,!=,&lt;,&lt; =,&gt;,&gt; =或者当子查询用作 表达。声明已经终止。
更新查询:
update Table1
set sizing = 0
where categoryid = 238
这个脚本有什么问题?
答案 0 :(得分:3)
DELETED
和INSERTED
表可能包含多行。
DELETED
- 包含修改前存在的数据(旧)INSERTED
- 修改后的数据(新)。所以你必须找出CategoryID
被改变的地方:
...
from
Inserted new
inner join
Deleted old on old.id = new.id
where
new.CategoryID <> old.CategoryID
要做一些事情,同时要记住可能有很多行,例如:
delete from [Table2] t2
where exists (select 1
from Inserted new
inner join Deleted old on old.id = new.id
where new.CategoryID <> old.CategoryID
and t2.ProductId = d.ProductID)
请注意ProductID
语句也可以更改UPDATE
。
答案 1 :(得分:1)
我认为以下问题是:
set @ocid=(select CategoryId from deleted)
SET
命令最多需要SELECT
语句中的1行。 deleted
表可能包含多行,因为触发器将在batch
级别触发,而不是record
级别。