使用插入值作为触发器

时间:2018-06-11 09:57:23

标签: sql sql-server

是否可以在SQL中的where子句中使用insert值?

我想以这种方式使用它:

create trigger t_wage_not_higher_than_30000
on transaction
as
if exists
(
select * 
from transaction
where ***inserted value*** >= 30000 and
description = employeewage
)
begin
raiserror('you cannot insert a wage higher than 30000')
rollback transaction
end

2 个答案:

答案 0 :(得分:2)

如果要检查值的范围,最好的方法是使用检查约束:

alter table transactions add constraint chk_transactions_value
    check (value < 30000);

没有理由编写用于检查数据值的触发器。

答案 1 :(得分:0)

对于此触发器,您应该只引用新插入的行。因此,您需要在语句中使用特殊触发器表。例如,

if exists (select * from inserted 
    where <some column you did not name in 
    your code> >= 30000 and description = 'employeewage') 
begin 
   raiserror ... (or throw);
   rollback tran;
   return;
end;

是的 - 约束通常是更好的方法。