我在t-sql中执行一个触发器,它会在每个INSERT,UPDATE或DELETE语句之后使'budget'表保持最新状态。 要在预算表中插入信息,我使用:
INSERT INTO budget (value) SELECT SUM(sal) FROM emp
我每次删除表只保留1条记录(我想在触发器上做同样的事情。
这是我的触发器的代码:
DROP TRIGGER licznik
go
CREATE TRIGGER licznik ON emp
FOR INSERT, UPDATE, DELETE
AS
DELETE FROM budget
DECLARE @sal_new INT ,
@sal_old INT
SELECT @sal_new = sal
FROM inserted
SELECT @sal_old = sal
FROM deleted
PRINT @sal_new
IF @sal_new > 0
BEGIN
UPDATE budget
SET value = value + @sal_new
END
IF @sal_old > 0
BEGIN
UPDATE budget
SET value = value - @sal_old
END
SET @sal_new = 0
SET @sal_old = 0
触发器不应该从开始计算整个预算,而是根据EMP表中的更改来增加或减少预算 - 这就是我更新行的原因。不幸的是它根本不起作用。
如何解决这个问题?
答案 0 :(得分:1)
create view BudgetView as
SELECT SUM(sal) FROM emp
除非emp只是令人兴奋,否则观点会很快 这些触发器给emp增加了很多开销
答案 1 :(得分:0)
这将处理设定的操作并相应地更新预算:
create trigger licznik on emp
for insert, update, delete
as
-- Make sure that there is a budget row to update.
if not exists ( select 42 from Budget )
insert into Budget ( Value ) values ( 0 );
-- Get the total of the adjustments.
declare @DeletedSum as Int;
declare @InsertedSum as Int;
select @DeletedSum = sum( Sal ) from deleted;
select @InsertedSum = sum( Sal ) from inserted;
-- Update the budget.
update Budget
set Value += Coalesce( @InsertedSum, 0 ) - Coalesce( @DeletedSum, 0 );