用于更新的SQL触发器

时间:2016-03-31 19:25:41

标签: sql tsql triggers

当我更新一行

时,我只想弄清楚如何做一个基本的触发器

继承人设置

CREATE TABLE marriage(
personid int
married varchar(20)
);

INSERT INTO marriage
values (1, unmarried);

我想要做的是创建一个sql触发器,这将使得当我更新一个人时只能从已婚到离婚但未婚未离婚。

如果有人可以帮我构建这个很棒的

3 个答案:

答案 0 :(得分:0)

如果有人在寻找类似的东西,那就是我在寻找的东西

alter trigger
trigtest3
on married
for update
as
begin
    declare @old varchar(20)
    declare @new varchar(20)

    select @old = married from deleted
    select @new = married from inserted
    if(@old like 'Unmarried' AND @new like 'Divorced')
        rollback
end

答案 1 :(得分:0)

不幸的是,SQL Server不提供每行触发器,但只触发完整命令。一个单独的更新命令可以更新多行,因此您必须查看至少有一个受影响的行是否已经过禁止更改。您可以通过在列或唯一标识记录(即主键)的列组合上加入deletedinserted伪表来执行此操作。

create trigger trg_upd_married on marriage for update as
begin
  declare @error_count int

  select @error_count = count(*)
  from deleted d
  join inserted i on i.id = d.id
  where d.married = 'Unmarried'
  where i.married = 'Divorced'

  if @error_count > 0
  begin
    raiserror('Unmarried persons cannot get divorced.', 16, 121)
    rollback transaction
  end
end;

上述触发器可能仍有错误。我不熟悉TSQL(并且注意到我发现它的触发器非常笨拙 - 至少与我习惯的Oracle触发器相比)。

答案 2 :(得分:0)

您需要使用而不是触发器来防止更新。对于更新触发器,在插入发生后运行。使用以下代码 -

create trigger abc on marriage
for instead of update
as
begin
Begin transaction
if exists(select 1 from deleted as a 
inner join inserted as b
on a.personid = b.personid
where a.married = 'unmarried' and b.married = 'Divorced')
begin
raiserror('Status can not be changed from unmarried to Divorced',16,1)
Rollback transaction
end
else
begin
update a
set a.married = b.married
from marriage as a
inner join inserted as b
on a.personid = b.personid
Commit transaction
end
end

如果有帮助,请告诉我