あなたの質問を理解していないかもしれませんが、トリガーは、データベースでイベントが発生したときに実行される手順です。このイベントは、トリガーを割り当てたテーブルで発生します。
この記事のサンプルを使用して、次のようなテーブルがあるとします。
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