2017-01-03 62 views
0

我試圖做一個觸發器,將更新一個表只如果事情是插在其他表SQL觸發器,應該更新其他表

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 

但是基於標識。 我的代碼沒有得到任何錯誤,但觸發似乎不起作用。我的錯誤是什麼?

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

+0

請與圖像停止。正如我在上次評論中所說的那樣,我嘗試了代碼並且工作正常。你只是沒有在創建觸發器後在** Purchases **表中插入值 – Lamak

回答

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

您應該使用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 
+0

我不知道爲什麼,但它沒有工作... – MitkoZ

+0

@MitkoZ也許你需要'ISNULL',就像在@M .Ali的回答 – Lamak

+0

嘗試過,但仍然沒有工作... – MitkoZ

0
  1. 您也可以使用EXISTS操作。
  2. 如果在該列中存在空值,則還需要注意MonthlySalesMade列中的可能NULLS列,+1 update列將不起作用。

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 
+0

idk爲什麼但它沒有工作.. – MitkoZ

+0

@MitkoZ你是什麼意思的'沒有工作'?你在想什麼? –

+0

http://i65.tinypic.com/2z4xz49.jpg – MitkoZ