4

我有两张桌子tbl_PurchaseDetailstbl_ItemDetails. tbl_ItemDetails我需要在from中插入一些行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. 它抛出以下错误:

消息 515,级别 16,状态 2,过程 trigger_UpdateItemDetails,第 11 行
无法将值 NULL 插入列“PurchaseID”,表“dbStockHandling.dbo.tbl_ItemDetails”;列不允许空值。插入失败。

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

4

1 回答 1

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

并确保您在tableNOT NULL的列中插入一个值。PurchaseIDtbl_PurchaseDetails

于 2013-03-06T05:43:09.303 回答