我有两张桌子tbl_PurchaseDetails
和tbl_ItemDetails
. tbl_ItemDetails
我需要在from中插入一些记录tbl_PurchaseDetails
,就在它插入之后tbl_PurchaseDetails
。tbl_PurchaseDetails
具有自动生成的自定义字段PurchaseID
。
自动生成的代码PurchaseID
是:-
*此触发器完美运行*
CREATE FUNCTION CreatePurchaseID (@id INT)
RETURNSvarchar(10)
AS
BEGIN
RETURN 'P' + CONVERT(VARCHAR(10), @id)
END
CREATE TRIGGER trigger_PurchaseID ON tbl_PurchaseDetails
FOR INSERT AS
UPDATE
tbl_PurchaseDetails
SET
tbl_PurchaseDetails.PurchaseID = dbo.CreatePurchaseID(tbl_PurchaseDetails.ID)
FROM
tbl_PurchaseDetails
INNER JOIN
INSERTED on tbl_PurchaseDetails.ID= INSERTED.ID
我已经为触发器编写了以下代码以插入tbl_ItemDetails
:-
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
成功添加。这里的问题是,PurchaseID
在tbl_ItemDetails
. 它按预期插入tbl_PurchaseDetails
。