如何根据行更新编写触发器

时间:2015-05-17 05:09:14

标签: sql sql-server-2008 sql-server-2008-r2

我第一次使用触发器,现在我遇到了一些问题,

我有3个表,InvoiceHead,InvoiceDetails,InventoryMaster。

当我更新InvoiceHead的“状态”字段(从0到1)时,需要根据更新的行更改InvoiceDetails和InventoryMaster的“状态”字段。

信赖: InvoiceHead_id = InvoiceDetails_id(FK)和 InventoryMaster_Processid = InvoiceHead_id(FK)

如何在InvoiceHead中编写触发器?

请帮忙解决这个问题..

1 个答案:

答案 0 :(得分:1)

试试这个

create trigger your_trigger
on InvoiceHead
after update
as
//declare @status int;
//select @status=i.status from inserted i;  
//IF @status == 1 
//BEGIN

update d
set d.status = b.status
from InvoiceDetails as d
join inserted as b 
on a.InvoiceDetails_id = b.InvoiceHead_id
where b.status == 1; 

update m
set m.status = b.status
from InventoryMaster  as m
join inserted as b 
on m.InventoryMaster_Processid = b.InvoiceHead_id
where b.status == 1;


end
go  

但请记住,在SQL触发器中,整个更新的工作方式与oracle中的rowwise不同。因此,如果此触发器一次触发超过一行,我的代码将无法满足您的要求。您需要对其进行微调..