如何在SQL中执行触发器?

时间:2014-11-19 12:18:57

标签: sql

我正在努力学习触发器,我知道如何做真正基本的触发器,但我无法解决这个问题。我有两个表服务(主)和销售。

Services(ServiceID,ServiceCost,SalesTotal)
Sales(TransactionID,TransactionDate,Amount,ServiceID)

我正在尝试为Update,Delete,Insert编写触发器。当您在Sales表中输入新的销售时,SalesTotal将根据ServiceID在Services表中更新。

前:

INSERT INTO Sales(TransactionID,TransactionDate,Amount,ServiceID)
VALUES ('16','2014-11-19','50','101');

因此,如果TransactionID'101'的SalesTotal为1000,那么在插入后它将是1050,如果我删除/更新则相反。

我想我必须使用连接表,但我目前感到难过。

2 个答案:

答案 0 :(得分:0)

使用此触发器,或拆分insert / dalete / update: 代码:

 CREATE TRIGGER [dbo].[t_Update_Services] on Sales AFTER UPDATE,INSERT, DELETE

AS

BEGIN

UPDATE a SET SalesTotal = SalesTotal - b.Amount FROM Services a JOIN deleted b ON a.ServiceID = b.ServiceID

UPDATE a SET SalesTotal = SalesTotal + b.Amount FROM Services a JOIN inserted b ON a.ServiceID = b.ServiceID

END

答案 1 :(得分:0)

在触发器中添加

BEGIN
if exists (select * from deleted)
begin
    UPDATE Services
     SET SalesTotal = SalesTotal - deleted.Amount
     FROM Services  
     JOIN deleted    ON Services.ServiceID = deleted.ServiceID
end 
else  
begin
    UPDATE Services
    SET SalesTotal = SalesTotal + inserted   .Amount
    FROM Services  
    JOIN inserted   ON Services.ServiceID = inserted.ServiceID
end
END