我编写了一个触发器,当MTRL表中的PRICER01列更新时,该触发器必须更新CCCMPMTRL表。表MTRL中的主键也是一个名为MTRL的列,我也保留在必须更新(CCCMPMTRL)作为外键的表中。问题是每当我更新MTRL表时,在CCCMPMTRL中,值都会更新我在MTRL中的所有记录,但我只想要一个,当前的一个。我做错了什么?
代码如下所示:
CREATE TRIGGER dbo.[test_Price]
ON dbo.[MTRL]
AFTER UPDATE
AS
DECLARE @MTRL INT;
DECLARE @OLDPRICER01 FLOAT(2);
DECLARE @NEWPRICER01 FLOAT(2);
DECLARE @MPMTRL INT;
SET @MTRL = (SELECT I.MTRL FROM INSERTED I,MTRL M WHERE M.MTRL = I.MTRL);
SET @MPMTRL = (SELECT MTRL FROM MTRL WHERE MTRL=@MTRL);
SET @OLDPRICER01 = (SELECT PRICER01 FROM MTRL WHERE MTRL =@MTRL AND SODTYPE = 51)
SET @NEWPRICER01 = (SELECT PRICER01 FROM INSERTED WHERE MTRL = @MTRL AND SODTYPE = 51)
IF(NOT EXISTS(SELECT CM.MTRL FROM CCCMPMTRL CM, INSERTED I WHERE CM.MTRL = I.MTRL))
INSERT INTO CCCMPMTRL
SELECT M.MTRL,D.PRICER01,I.PRICER01 FROM INSERTED I, DELETED D, MTRL M WHERE I.MTRL = @MTRL
ELSE
IF(@OLDPRICER01 <> @NEWPRICER01)
UPDATE CCCMPMTRL
SET OLDPRICER01 = @OLDPRICER01,
NEWPRICER01 = @NEWPRICER01
FROM CCCMPMTRL AS CM
WHERE CM.MTRL = @MTRL
答案 0 :(得分:2)
试试这个
UPDATE CM
SET OLDPRICER01 = D.PRICER01,
NEWPRICER01 = I.PRICER01
FROM INSERTED I
JOIN DELETED D ON D.MTRL=I.MTRL
JOIN CCCMPMTRL CM ON CM.MTRL=I.MTRL
WHERE D.PRICER01 <> I.PRICER01
INSERT INTO CCCMPMTRL
SELECT I.MTRL, D.PRICER01, I.PRICER01
FROM INSERTED I
JOIN DELETED D ON D.MTRL=I.MTRL
LEFT JOIN CCCMPMTRL C ON C.MTRL=I.MTRL
WHERE C.MTRL IS NULL
因为UPDATE语句在CCMPMTRL上使用内连接,所以它只会更新已存在行的位置,而INSERT语句使用左外连接来排除MTRL的现有值。
无论是一次插入一行还是多行,这都应该有效,并且不需要所有这些局部变量。