我有两张表tbl_PurchaseDetails
和tbl_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
?
答案 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
。