【问题标题】:Best way to use trigger to prevent deletion of a row where condition in another table is met?使用触发器防止删除满足另一个表中条件的行的最佳方法?
【发布时间】:2020-05-13 21:13:31
【问题描述】:

如果满足 table_2 行中具有相同 table_1ID 的条件(table_2.status = 'ON'),我想创建一个触发器以防止删除 table_1 中的行。

我不担心一次删除多于一行。

最好的方法是什么?

提前致谢。

【问题讨论】:

  • 你的表1中的DELETE语句可以JOIN到表2的ID上,你可以添加where条件where table2.status 'ON'。这将删除状态 'ON' 的所有行。是否符合您的要求?
  • @DanielG 我不是要删除行,而是创建一个触发器,以防止删除 table_1 中的行,如果它的 table_2.status 为“ON”,则每当尝试删除时。跨度>
  • @DanielG 非常感谢您的帮助。

标签: sql postgresql join sql-delete database-trigger


【解决方案1】:

这是一种方法:

create or replace function func_delete_table1()
returns trigger as 
$$
begin
    if exists (select 1 from table2 where table1_id = old.id and status = 'ON') then
        raise exception 'Cannot delete id % from table1 because the corresponding record in table2 has status ON', new.id;
    end if;
end
$$ language 'plgpsql';

create trigger trg_delete_table1 before delete on table1_id
for each row execute procedure func_delete_table1();

请注意,正如 DanielG 所说,您还可以在 delete 语句中实现整个逻辑:

delete from table1 t1
where 
    id = ?
    and not exists (select 1 from table2 t2 where t2.table1id = t2.id and t2.status = 'ON')

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-02-23
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多