觸發

2010-11-10 39 views
0

我有一個定義之間的許多一對多的關係,例如,CustomerOrders,像這樣的中間表中選擇已刪除表中的特定行:觸發

USE [master] 
GO 

CREATE DATABASE Example 
GO 

USE [Example] 
GO 

CREATE TABLE [dbo].[CustomerOrders](
    [CustomerId] [int], 
    [OrderId] [int] 
) 
GO 

INSERT INTO CustomerOrders (CustomerId, OrderId) VALUES (1, 1) 
INSERT INTO CustomerOrders (CustomerId, OrderId) VALUES (1, 2) 
INSERT INTO CustomerOrders (CustomerId, OrderId) VALUES (2, 1) 
GO 

CREATE TRIGGER [dbo].[CustomerOrdersRemoved] 
    ON [dbo].[CustomerOrders] 
    FOR DELETE 
AS 
    BEGIN 
    SET NOCOUNT ON; 

    --IF NOT EXISTS (SELECT CustomerId FROM CustomerOrders 
        INNER JOIN deleted ON CustomerOrders.CustomerId=deleted.CustomerId) 
    --this wont work 
END 
GO 

DELETE CustomerOrders WHERE OrderId=1 
GO 

現在,我需要有在此表上觸發一個ON DELETE觸發器,這將需要更新另一個表,其基於客戶誰有任何訂單留在表中。在這種情況下,在DELETE操作之後,CustomerId=1的客戶將有1個訂單,剩餘訂單號碼爲OrderId=2,客戶訂單號爲CustomerId=2的訂單沒有剩餘訂單。所以我只需要取得客戶CustomerId=2刪除vtable在觸發器內。

我該如何做到這一點?

回答

0

我的手比我的頭快: -/

答案是

SELECT CustomerId FROM deleted WHERE CustomerId NOT IN (SELECT CustomerId FROM CustomerOrders)

1

的問題是,你在比較的右邊使用deleted.CustomerId。

我正在做類似於你正在做的事情。

並且解決方案是定義一個@variable來保存deleted.CustomerId(在您的SET NO COUNT行之後),然後將CustomerOrders.CustomerId與該變量進行比較。

編輯: 這是代碼,它工作得很好,它是一個觸發器更新電影等級,它從tblRating(MovieID,UserID,rating)得到的平均評分也代表了tblMovies之間的多對多關係和向tblUsers,這個軟件需要插入,但它與刪除相同:

CREATE TRIGGER trUpdateRating 
ON [dbo].[tblRating] 
AFTER INSERT 
AS 
BEGIN 
SET NOCOUNT ON 
DECLARE @rate float, @mid int 
SET @rate = 0; 

-- here is the assignment I was talking about and it is valid 
SELECT @mid=MovieID from inserted; 

SELECT @rate=AVG(isnull(Rating, 0)) FROM tblRating WHERE [email protected]; 

-- and here is the comparison 
UPDATE tblMovies 
SET avg_rating = @rate 
WHERE [email protected]; 
END 
+0

你不能做這樣的事:@變量=(SELECT客戶編號已刪除),因爲它會拋出時,觸發將在刪除被解僱多行,因爲它們不能被分配給1個變量。 – kateroh 2010-11-10 23:59:24

+0

我看,情況不一樣。 – 2010-11-11 00:14:41