我第一次在桌子上创建了一个触发器。
当记录插入我的TableA时,触发器会将新记录插入同一个TableA。
当我插入符合语句中设置条件的记录时,触发器会被正确操作。
当我插入不符合这些条件的记录时,触发器不会被操作。
问题是,如果我现在再次添加符合条件的新记录,则不会再触发该触发器。当我插入不符合条件的记录时,它似乎停止工作。
如果我删除了第2点中添加的记录,如果不满足条件,则它会再次开始工作。很奇怪,无法理解。有什么建议吗?
场景:当客户第一次购买属于StockType=1
的商品时,新产品将添加到同一发票中。它工作正常。
如果客户购买了不属于StockType=1
的其他产品,则不会触发该触发器。这很好。
之后,触发器将不再被执行。这是原始的声明代码。
SET NOCOUNT ON;
DECLARE @SerialNo NVARCHAR(50)
SET @SerialNo = (SELECT TOP 1 SNSerialNoTx
FROM T_SNSerialNo
WHERE (SNStockItemID = 7058 AND SNInvoiceID_N IS NULL))
INSERT INTO T_IIInvoiceItem (IIInvoiceID, IIProfitCenterID, IIStockItemID, IISerialNoTx_N,
IIQtyIn, IICostPriceCompsTx, IITaxBandIDsTx, IITaxRatesTx,
IIStockNoTx, IIStockItemTx, IIStockTypeID, IIStockTypeTx,
IIManufacturerID, IIManufacturerTx, IICustID)
SELECT
IIInvoiceID, 23, 7058, @SerialNo,
IIStockTypeID, '-1:1@0', 0, 0,
'Training.EUCS',
(SELECT 'Online Training (SN:'+@SerialNo+')'), 40,'Online Training', 7, 'Company', IICustID
FROM inserted
WHERE IIStockTypeID = 1
AND IICustID IN (SELECT IICustID
FROM T_IIInvoiceItem
INNER JOIN T_InInvoice ON InInvoiceID = IIInvoiceID
INNER JOIN T_CuCust ON CuCustID = IICustID
WHERE IIStockTypeID = 1 AND InTransStatusID = 0
GROUP BY IICustID
HAVING COUNT(IICustID) = 1)
触发代码
ALTER TRIGGER [dbo].[SerialTrigger]
ON [dbo].[T_IIInvoiceItem]
AFTER INSERT
答案 0 :(得分:1)
试试这个(每个@DeepDiver):
SET NOCOUNT ON;
--**********************************************
SET TRANSACTION ISOLATION LEVEL READ UNCOMMITTED
--**********************************************
DECLARE @SerialNo NVARCHAR(50)
-- -----------------------------------------------------
SELECT TOP 1 @SerialNo = SNSerialNoTx
FROM T_SNSerialNo
WHERE SNStockItemID = 7058
AND SNInvoiceID_N IS NULL ;
-- -----------------------------------------------------
; WITH ins
AS (
SELECT IIInvoiceID, IIStockTypeID, IICustID
FROM Inserted
WHERE IIStockTypeID = 1
AND IICustID IN (
SELECT IICustID
FROM T_IIInvoiceItem
INNER JOIN T_InInvoice ON InInvoiceID = IIInvoiceID
INNER JOIN T_CuCust ON CuCustID = IICustID
WHERE IIStockTypeID = 1
AND InTransStatusID = 0
GROUP BY IICustID
HAVING COUNT(IICustID) = 1
)
)
-- -----------------------------------------------------
INSERT INTO T_IIInvoiceItem (IIInvoiceID, IIProfitCenterID, IIStockItemID, IISerialNoTx_N,
IIQtyIn, IICostPriceCompsTx, IITaxBandIDsTx, IITaxRatesTx,
IIStockNoTx, IIStockItemTx, IIStockTypeID, IIStockTypeTx,
IIManufacturerID, IIManufacturerTx, IICustID)
SELECT
IIInvoiceID
, 23
, 7058
, @SerialNo
, IIStockTypeID
, '-1:1@0'
, 0
, 0
, 'Training.EUCS'
, 'Online Training (SN:'+@SerialNo+')'
, 40
,'Online Training'
, 7
, 'Company'
, IICustID
FROM ins