1

您能否根据插入、更新或删除的来源运行触发器?

UPD

也许我对上面的问题不太清楚。我希望触发器仅在插入来自特定表时运行。例如,我有两个插入 TABLE MAIN 的表。如果插入来自表 A,我只希望触发器运行。如果它来自表 B,则不要运行。

我想我可以使用表 A 的连接?以前从未以这种方式使用过触发器。

4

1 回答 1

1

也许我不理解您的问题,但触发器是在数据库中发生事件时执行的过程。此事件发生在您已将触发器分配到的表上。

使用本文中的示例,假设您有这样的表:

CREATE TABLE Customers (
 CustomerId smallint identity(1,1),
 Name nvarchar(255),
 Priority tinyint
)

CREATE TABLE Sales (
 TransactionId smallint identity(1,1),
 CustomerId smallint,
 [Net Amount] int,
 Completed bit
)

您可以创建一个类似于此的触发器,它将执行AFTER INSERT, UPDATE and DELETE

CREATE TRIGGER dbo.Update_Customer_Priority
 ON dbo.Sales
AFTER INSERT, UPDATE, DELETE
AS

WITH CTE AS (
 select CustomerId from inserted
 union
 select CustomerId from deleted
)
UPDATE Customers
SET
 Priority =
  case
   when t.Total < 10000 then 3
   when t.Total between 10000 and 50000 then 2
   when t.Total > 50000 then 1
   when t.Total IS NULL then NULL
  end
FROM Customers c
INNER JOIN CTE ON CTE.CustomerId = c.CustomerId
LEFT JOIN (
 select
  Sales.CustomerId,
  SUM([Net Amount]) Total
 from Sales
 inner join CTE on CTE.CustomerId = Sales.CustomerId
 where
  Completed = 1
 group by Sales.CustomerId
) t ON t.CustomerId = c.CustomerId

GO
于 2012-12-24T21:20:00.813 回答