创建一个触发器,将表中的记录插入另一个表。在触发器中获取插入的值

时间:2013-03-06 05:40:18

标签: sql sql-server

我有两张表tbl_PurchaseDetailstbl_ItemDetails。在tbl_ItemDetails中插入tbl_PurchaseDetails之后,我需要在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
  无法将值NULL插入列'PurchaseID',表'dbStockHandling.dbo.tbl_ItemDetails';列不允许空值。 INSERT失败。

我的问题是如何从tbl_PurchaseDetails获取插入的值,以便触发器可以将它们插入tbl_ItemDetails

1 个答案:

答案 0 :(得分:6)

请尝试:

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值插入表PurchaseID的列tbl_PurchaseDetails