【问题标题】:How to fire trigger after every insert in sql server table automatically?如何在每次插入 sql server 表后自动触发触发器?
【发布时间】:2015-01-27 10:18:54
【问题描述】:

我是 SQL Server 触发器的新手。我最近遇到一个问题,我有两个名为tbl_Itemtbl_changePrice 的表。当tbl_changeprice 插入新行时,我想更新tbl_Item。使用此新行名称,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

【问题讨论】:

  • 您的触发器有 MAJOR 缺陷,因为您似乎认为它会每行调用一次 - 那是不是 b> 情况。触发器每个语句触发一次,因此如果您的 UPDATE 语句影响 25 行,您将触发触发器一次,然后是 Inserted 和 @987654329 @ 每个将包含 25 行。您的代码将在这 25 行中选择哪一行? select @itemname=i.name from inserted i; - 这是不确定的。您需要重写触发器以考虑到这一点!

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


【解决方案1】:

要处理一次插入的多行 - 您需要重写触发器以便能够处理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

【讨论】:

    猜你喜欢
    • 2011-12-06
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-11-09
    • 1970-01-01
    相关资源
    最近更新 更多