如何在sql server表中每次插入后自动触发触发器?

时间:2015-01-27 10:18:54

标签: sql sql-server database stored-procedures triggers

我是SQL Server触发器的新手。我最近遇到一个问题,我有两个名为tbl_Itemtbl_changePrice的表。我想在tbl_Item插入新行时更新tbl_changeprice。使用此新行名称,相同的日期数据将在tbl_item表中更新。

以下是我尝试更新表格的触发器:

Alter TRIGGER trgAfterInsert ON [dbo].[tbl_changePrice] 
After insert
AS
    declare @itemname int;
    declare @saleprice decimal(18,2);
    declare @buyprice decimal(18,2);

    select @itemname=i.name from inserted i;    
    select @saleprice=i.saleprice from inserted i;  
    select @buyprice=i.pprice from inserted i;  

    update tbl_Item set sellingPrice= @saleprice, buyingPrice= @buyprice where name= @itemname

    PRINT 'AFTER INSERT trigger fired.'
GO

1 个答案:

答案 0 :(得分:5)

要同时处理多行 - 您需要重写触发器才能处理Inserted中的多行 - 类似这样的内容:

ALTER TRIGGER trgAfterInsert 
ON [dbo].[tbl_changePrice] 
AFTER INSERT
AS
    UPDATE dbo.tbl_Item 
    SET sellingPrice = i.saleprice, buyingPrice = i.pprice 
    FROM Inserted i
    WHERE tbl_Item.name = i.name

    PRINT 'AFTER INSERT trigger fired.'
GO