我有这个存储过程:
CREATE PROCEDURE getManagerSalary
(
@Emp_id INT,
@ManagerSalary MONEY OUTPUT
)
AS
SELECT @ManagerSalary = es.Salary
FROM [outdoorparadise].[dbo].[Employee] AS e
INNER JOIN
[outdoorparadise].[dbo].[Employee] AS m
ON e.Manager_id = m.Emp_id
INNER JOIN
[outdoorparadise].[dbo].[Employee_staff] AS es
ON e.Manager_id = es.Emp_staff_code
WHERE e.Emp_id = @Emp_id;
我得到了这个触发器:
CREATE TRIGGER checkSalary ON Employee_staff
AFTER UPDATE
AS
DECLARE
@Emp_id INT,
@NewSalary MONEY,
@ManagerSalary MONEY;
SELECT @NewSalary = Salary
FROM inserted;
SELECT @Emp_id = Emp_staff_code
FROM inserted;
EXEC getManagerSalary @Emp_id = @Emp_id,
@ManagerSalary = @ManagerSalary OUTPUT;
IF @NewSalary > @ManagerSalary
BEGIN
RAISERROR 60000 'Salary cannot be higher than the salary of the manager!'
ROLLBACK TRANSACTION;
END
ELSE
COMMIT TRANSACTION;
当我将薪水更新为高于经理薪水的值时,我得到加薪错误+此错误:交易在触发器中结束。批次已中止。
当我尝试将薪水更新为低于经理薪水的价值时,我仍然得到:交易在触发器中结束。批次已中止。
有人可以告诉我如何解决这个问题? 我搜索过,但找不到任何东西。
谢谢, Ryuken
PS:这是我的第一篇文章,也许我没有用正确的方式粘贴代码,所以很抱歉。
答案 0 :(得分:3)
抛弃扳机。用检查约束和标量函数替换它。
CREATE FUNCTION dbo.GetManagerSalary(@Emp_id int) RETURNS money
AS
BEGIN
RETURN
SELECT es.Salary
FROM [dbo].[Employee] e
JOIN [dbo].[Employee] m ON m.Emp_id = e.Manager_id
JOIN [dbo].[Employee_staff] es ON es.Emp_staff_code = e.Manager_id
WHERE e.Emp_id = @Emp_id;
END
GO
ALTER TABLE Employee_staff
ADD CONSTRAINT CK_Salary
CHECK (ISNULL([Salary], 0) <= ISNULL(dbo.GetManagerSalary([Salary]), 1e9)))