CREATE TRIGGER UT_GoodInDetail_UDI ON tPurInDetail /*建立采购进货触发器*/
FOR DELETE , INSERT , UPDATE
AS
BEGIN
DECLARE @IBillNo_I VARCHAR (20) , @IProdNO_I VARCHAR(20) , @ISTORENO_I VARCHAR(20) , @QTN_I Numeric (8,0)
DECLARE @IBillNo_D VARCHAR (20) , @IProdNO_D VARCHAR(20) , @ISTORENO_D VARCHAR(20) , @QTN_D Numeric (8,0)
UPDATE tStorage Set Qtn = 0 WHERE Qtn IS NULL /*库存量中如果为NULL,则置为0;*/
--删除触发操作开始--
DECLARE DELETED_CURSOR CURSOR FOR /*删除临时表DELETED的游标*/
SELECT BILLNO ,StoreNo, ProdNo , Qtn FROM DELETED /*操作时,tPurInDetail中的临时表DELETED;*/
OPEN DELETED_CURSOR /*打开游标*/
FETCH NEXT FROM DELETED_CURSOR INTO @IBillNo_D ,@ISTORENO_D, @IProdNO_D , @QTN_D /*获取数据到变量中*/
WHILE @@FETCH_STATUS = 0 /*获取状态正常*/
BEGIN
/*iStore:仓库编号;从表中找仓库编号,满足条件:进货单编号等于DELETED临时表中的编号;
//确定库存表中有无相应记录,有则更新,无则插入;(以减的运算方式)*/
IF EXISTS(SELECT * FROM tStorage WHERE StoreNo = @ISTORENO_D AND ProdNo = @IProdNO_D)
UPDATE tStorage Set Qtn = Qtn - @QTN_D WHERE StoreNo = @ISTORENO_D AND ProdNo = @IProdNO_D
ELSE
INSERT INTO tStorage (StoreNo , ProdNo , Qtn ) VALUES ( @ISTORENO_D , @IProdNO_D , - @QTN_D )
FETCH NEXT FROM DELETED_CURSOR INTO @IBillNo_D ,@ISTORENO_D, @IProdNO_D , @QTN_D /*取下一记录;*/
END
CLOSE DELETED_CURSOR
DEALLOCATE DELETED_CURSOR
--删除触发操作完成--
--插入触发操作开始--
DECLARE INSERTED_CURSOR CURSOR FOR
SELECT BillNo ,StoreNo, ProdNo , Qtn FROM INSERTED /*插入临时表:INSERTED;*/
OPEN INSERTED_CURSOR
FETCH NEXT FROM INSERTED_CURSOR INTO @IBillNo_I ,@ISTORENO_I, @IProdNO_I , @QTN_I
WHILE @@FETCH_STATUS = 0 /*获取状态正常*/
BEGIN
/*存在则更新,不存在则插入;(以加的运算方式)*/
IF EXISTS(SELECT * FROM tStorage WHERE StoreNo = @ISTORENO_I AND ProdNo = @IProdNO_I)
UPDATE tStorage Set Qtn = Qtn + @QTN_I WHERE StoreNo = @ISTORENO_I AND ProdNo = @IProdNO_I
ELSE
INSERT INTO tStorage (StoreNo , ProdNo , Qtn ) VALUES ( @ISTORENO_I ,@IProdNO_I ,@QTN_I)
/*从临时表中获取下一记录*/
FETCH NEXT FROM INSERTED_CURSOR INTO @IBillNo_I ,@ISTORENO_I, @IProdNO_I , @QTN_I
END
CLOSE INSERTED_CURSOR
DEALLOCATE INSERTED_CURSOR
DELETE FROM tStorage WHERE Qtn = 0 /*当商品库存量为0时,则删除相应记录;*/
END