应该更新其他表的SQL触发器

时间:2017-01-03 14:56:50

标签: sql sql-server tsql

我正在尝试创建一个触发器,只有在其他表中插入了某些内容时才会更新表

CREATE TABLE Purchases
(
PurchaseID INT IDENTITY NOT NULL PRIMARY KEY,
DateBought SMALLDATETIME,
Price MONEY CHECK (Price>0),
RealEstateID INT UNIQUE NOT NULL,
DealMadeByEmployeeID INT NOT NULL
);


INSERT INTO Purchases(DateBought, Price, RealEstateID, DealMadeByEmployeeID)
VALUES ('20161015 15:10:03','120000',3, 3); --Апартамент 170 квадратни метра

INSERT INTO Purchases(DateBought, Price, RealEstateID, DealMadeByEmployeeID)
VALUES ('20161219 13:13:30','200000',4, 3); --Къща 500 квадратни метра

INSERT INTO Purchases (Price,RealEstateID,DealMadeByEmployeeID)
VALUES ('130000',6,3); --непродаден апартамент

CREATE TABLE EmployeesSalary
(
EmployeeID INT NOT NULL PRIMARY KEY,
CurrentSalary MONEY DEFAULT 0,-- на процент
MonthlySalesMade INT DEFAULT 0,
MonthlyRentsMade INT DEFAULT 0
);

INSERT INTO EmployeesSalary (EmployeeID, CurrentSalary)
VALUES (1, '400');

INSERT INTO EmployeesSalary (EmployeeID, CurrentSalary)
VALUES (2, '400');

INSERT INTO EmployeesSalary (EmployeeID, CurrentSalary)
VALUES (3, '400');

CREATE TRIGGER tr_EmployeesSalaryPurchasesUpdate --при INSERT в Purchases таблицата
ON Purchases
AFTER INSERT
AS
BEGIN
    UPDATE EmployeesSalary
    SET EmployeesSalary.MonthlySalesMade=EmployeesSalary.MonthlySalesMade+1
    WHERE EmployeesSalary.EmployeeID IN (SELECT inserted.DealMadeByEmployeeID FROM inserted)
END

但基于ID。 我的代码没有任何错误,但触发器似乎不起作用。我的错是什么?

https://postimg.org/image/rot0xcriv/

3 个答案:

答案 0 :(得分:2)

你应该在那里使用INNER JOIN

CREATE TRIGGER tr_EmployeesSalaryPurchasesUpdate --при INSERT в Purchases таблицата
ON Purchases
AFTER INSERT
AS
BEGIN
    UPDATE ES 
    SET ES.MonthlySalesMade = ES.MonthlySalesMade+1
    FROM EmployeesSalary ES
    INNER JOIN INSERTED I
        ON ES.EmployeeID = I.DealMadeByEmployeeID;
END

答案 1 :(得分:1)

除非NOCOUNT设置为ON,否则如果有多个更新,它将无法工作:

CREATE TRIGGER tr_EmployeesSalaryPurchasesUpdate 
ON Purchases
AFTER INSERT
AS
BEGIN
    SET NOCOUNT ON -- new line of code
    UPDATE EmployeesSalary
    SET EmployeesSalary.MonthlySalesMade=EmployeesSalary.MonthlySalesMade+1
    WHERE EmployeesSalary.EmployeeID IN (SELECT inserted.DealMadeByEmployeeID FROM inserted)
END

答案 2 :(得分:0)

  1. 您还可以使用EXISTS运算符。
  2. 还要注意MonthlySalesMade列中可能存在的NULLS,如果该列中存在空值,则+1 update将无效。
  3. CREATE TRIGGER tr_EmployeesSalaryPurchasesUpdate 
    ON Purchases
    AFTER INSERT
    AS
    BEGIN
        UPDATE EmployeesSalary
        SET MonthlySalesMade = ISNULL(MonthlySalesMade, 0)+1
        WHERE EXISTS (SELECT 1 
                      FROM inserted
                      WHERE EmployeesSalary.EmployeeID = inserted.DealMadeByEmployeeID )
    END