我有一张表INVENTORY
Create table INVENTORY(){
INVENID int indentity, -- inventory ID
PRODUCTID varchar(10), --product id
QUANTUM int, -- quantum
QUANTUMINPUT int, -- quantum input
QUANTUMOUTPUT int, -- quantum output
}
我创建了触发器:
Create trigger trig_cal
on INVENTORY
after insert,update
as
if(UPDATE(QUANTUMINPUT))
begin
UPDATE INVENTORY set QUANTUM = QUANTUM + QUANTUMINPUT
end
else if(UPDATE(QUANTUMOUTPUT))
begin
UPDATE INVENTORY set QUANTUM = QUANTUM - QUANTUMOUTPUT
end
我尝试插入Insert into INVENTORY(PRODUCTID,QUANTUM) values('P01',100)
然后UPDATE INVENTORY set QUANTUMOUTPUT = 1 where PRODUCTID = 'P01'
它返回QUANTUM
= 90。这是不对的
但是,当我更新QUANTUMOUTPUT
或QUANTUMINPUT
时,计算错误
答案 0 :(得分:0)
尝试使用此触发器代码
CREATE TABLE INVENTORY
(
INVENID INT,-- inventory ID
PRODUCTID VARCHAR(10),--product id
QUANTUM INT,-- quantum
QUANTUMINPUT INT,-- quantum input
QUANTUMOUTPUT INT, -- quantum output
)
ALTER TRIGGER trig_cal
ON INVENTORY
after UPDATE
AS
IF( UPDATE(QUANTUMINPUT) )
BEGIN
UPDATE INV
SET INV.QUANTUM = INS.QUANTUM + INS.QUANTUMINPUT
FROM INVENTORY INV
JOIN INSERTED INS
ON ISNULL(INS.INVENID, 0) = ISNULL(INV.INVENID, 0)
AND ISNULL(INS.PRODUCTID, 0) = ISNULL(INV.PRODUCTID, 0)
END
ELSE IF( UPDATE(QUANTUMOUTPUT) )
BEGIN
UPDATE INV
SET INV.QUANTUM = INS.QUANTUM - INS.QUANTUMOUTPUT
FROM INVENTORY INV
JOIN INSERTED INS
ON ISNULL(INS.INVENID, 0) = ISNULL(INV.INVENID, 0)
AND ISNULL(INS.PRODUCTID, 0) = ISNULL(INV.PRODUCTID, 0)
END
INSERT INTO INVENTORY
(PRODUCTID,
QUANTUM)
VALUES ('P01',
100)
UPDATE INVENTORY
SET QUANTUMOUTPUT = 1
WHERE PRODUCTID = 'P01'
UPDATE INVENTORY
SET QUANTUMINPUT = 1
WHERE PRODUCTID = 'P01'