create trigger [dbo].[purchase_delete]
on [dbo].[purchase]
after Delete
as
begin
delete from pcDetails where pc_id=(select purchase_id from deleted)
end
执行下面这句后,执行触发器purchase_delete:
delete from purchase purchase_id =3
但是我在表pcDetails中:
pc_id=3
的数据不只一条这样我的触发器就出问题求帮帮忙??
------解决方案--------------------
create trigger [dbo].[purchase_delete]
on [dbo].[purchase]
after Delete
as
begin
--delete from pcDetails where pc_id=(select purchase_id from deleted)
delete from pcDetails where pc_id IN (select purchase_id from deleted) ---->不能用等号,等号一对一没有错,但一对多时就会报错.
end
原则上,你做删除时,应该先删除明细表,再删除主表.
但是插入数据时,应该先插入主表, 再插入子表数据
------解决方案--------------------
pcDetails是有另一条触发的,
create TRIGGER [dbo].[pc_delete]
ON [dbo].[pcDetails]
AFTER DELETE
AS
BEGIN
UPDATE a
SET QTY=QTY-b.qty
from store a
left join (select pc_id ,sum(qty) as qty from deleted group by pc_id )b
on a.pc_id =b.pc_id
where store.pd_id in(select pd_id from deleted)
END
这里是根据删除pcDetails表里的数据来执行的,pcDetails表的pd_id与store表的pd_id是相同的。
------解决方案--------------------
create TRIGGER [dbo].[pc_delete]
ON [dbo].[pcDetails]
AFTER DELETE
AS
BEGIN
UPDATE a
SET QTY=QTY-b.qty
from store a
left join (select pd_id ,sum(qty) as qty from deleted group by pd_id )b