2013-03-06 65 views
3

我有兩個表tbl_PurchaseDetailstbl_ItemDetails。我需要從tbl_PurchaseDetails插入tbl_ItemDetails的一些行,插入tbl_PurchaseDetails之後。我知道這個問題,但我無法解決它。請幫忙。創建一個觸發器,將表中的記錄插入另一個表中。獲取插入的值在觸發器中

我已經寫了扳機下面的代碼:

CREATE TRIGGER trigger_UpdateItemDetails ON tbl_PurchaseDetails 
FOR INSERT AS 
DECLARE @PurchaseID VARCHAR(20) 
DECLARE @Quantity INT 
DECLARE @WarehouseID VARCHAR(20) 

SELECT @PurchaseID=(PurchaseID) FROM INSERTED 
SELECT @Quantity=(ItemQuantity) FROM INSERTED 
SELECT @WarehouseID=(WarehouseID) FROM INSERTED 

INSERT INTO 
tbl_ItemDetails 
(PurchaseID,Quantity,WarehouseID) 
VALUES 
(
@PurchaseID,@Quantity,@WarehouseID 
) 

,現在當我插入tbl_PurchaseDetails的行添加到tbl_PurchaseDetails而不是tbl_ItemDetails。它引發以下錯誤:

Msg 515, Level 16, State 2, Procedure trigger_UpdateItemDetails, Line 11
Cannot insert the value NULL into column 'PurchaseID', table 'dbStockHandling.dbo.tbl_ItemDetails'; column does not allow nulls. INSERT fails.

我的問題是如何從tbl_PurchaseDetails使得觸發可以將它們插入到tbl_ItemDetails得到插入的值?

回答

3

請嘗試:

CREATE TRIGGER trigger_UpdateItemDetails ON tbl_PurchaseDetails 
FOR INSERT AS 
BEGIN 

    INSERT INTO 
    tbl_ItemDetails 
    (
     PurchaseID, 
     Quantity, 
     WarehouseID 
    ) 
    SELECT 
     PurchaseID, 
     ItemQuantity, 
     WarehouseID 
    FROM 
     INSERTED 
END 

,並確保您插入NOT NULL值表tbl_PurchaseDetailsPurchaseID列。

+0

非常感謝您的回覆。其實這兩個觸發器都能正常工作。我想'tbl_ItemDetails'中的自動增量字段,我沒有實現,這就是錯誤發生的原因。再次感謝你。 :d – 2013-03-06 06:04:22

相關問題