您需要停下來重新開始。
首先,您需要趕上AFTER UPDATE
事件 - 而不是插入 - 因爲您想在薪水更新時(現有值替換爲更高的值)執行某些操作。
其次,觸發器就會被調用一次每UPDATE
聲明,如果UPDATE
影響超過一個排,Deleted
和Inserted
僞表將包含多行數據 - 讓你的SELECT @Salary = salary FROM Inserted
聲明註定 - 它會取一個任意排並忽略所有可能受到影響的其他人。
在UPDATE
情況下,Inserted
將具有新值(更新之後),而Deleted
具有舊值(更新之前) - 所以這兩個僞表之間的差異可被用於圖如果出工資增幅超過了20%!
CREATE TRIGGER trBusDriverSalaryIncrease
ON dbo.Bus_Driver
AFTER UPDATE
AS
BEGIN
-- declare a table variable to hold all revelant values
DECLARE @RelevantIncreases TABLE (drNo INT, StationNo INT, SalaryIncrease DECIMAL(18,2))
-- find those bus drivers who have had a more than 20% increase in their salary
INSERT INTO @relevantIncreases (drNo, StationNo, SalaryIncrease)
SELECT
i.drNo, i.StationNo, -- Driver and Station No
(i.Salary - d.Salary) -- Salary increase in absolute numbers
FROM
Deleted d
INNER JOIN
Inserted i ON d.drNo = i.drNo
WHERE
-- Salary increased by more than 20%
i.Salary > 1.2 * d.Salary
-- now that we have all the relevant bus drivers and their salary increase
-- insert this into the Station.Salary_Commission column
UPDATE s
SET Salary_Commission = s.Salary_Commission + ri.SalaryIncrease * 0.0005
FROM dbo.Station s
INNER JOIN @RelevantIncreases ri ON ri.StationNo = s.StationNo
END
根據Microsoft準則,超過五張表不允許加入SQL Server。這是對的嗎?如果不正確,按照您的觀點,允許在SQL Server中允許加入多少表以獲得更好的性能。 – RGS