📜  PostgreSQL DROP触发器

📅  最后修改于: 2020-11-30 09:29:53             🧑  作者: Mango

PostgreSQL DROP触发器

在本节中,我们将了解PostgreSQL DROP TRIGGER命令的工作原理,并查看从PostgreSQL中的指定表删除和删除触发器的示例。

什么是PostgreSQL Drop Trigger命令?

在PostgreSQL中,我们可以使用Drop Trigger命令删除现有的trigger

PostgreSQL Drop Trigger命令的语法

下图用于从特定表中删除触发器:

DROP TRIGGER [IF EXISTS] trigger_name 
ON table_name [ CASCADE | RESTRICT ];

在以上语法中,我们使用了以下参数:

Parameters Description
Trigger_name
  • It is used to define the trigger name that we need to remove, and it is mentioned after the DROP TRIGGER keyword.
If EXISTS
  • The If EXISTS parameter is used to remove the trigger temporarily only if it exists.
  • And if we try to remove a non-existing trigger without specifying the IF EXISTScommand, we will get an error in the result.
  • PostgreSQL issues a notice as an alternative if we use the IF EXISTS to remove a non-existing trigger.
Table_name
  • The table name parameter is used to define the table name where the trigger belongs.
  • If the table is linked to a defined schema, we can use the table’s schema-qualified name, such as schema_name.table_name.
CASCADE
  • If we want to drop objects, which automatically rely on the trigger, we can use the CASCADE option.
RESTRICT
  • We can use the RESTRICT option if any objects depend on trigger or we want to refuse or drop that trigger.
  • The DROP TRIGGER command uses the RESTRICT option by default.

注意:在SQL中,触发器名称不仅限于表,因此,我们可以使用以下命令:

DROP TRIGGER trigger_name;

PostgreSQL Drop Trigger命令示例

让我们看一个简单的示例,以了解PostgreSQL DROP Trigger命令的工作。

为此,我们采用了Employee表,该表是在PostgreSQL教程的前面部分中创建的。

步骤1:建立新函数

首先,我们将创建一个函数,该函数检查雇员的emp_name ,其中雇员长度的名称必须至少为10,并且不能为null。

CREATE FUNCTION check_emp_name()
    RETURNS TRIGGER
AS $$
BEGIN
IF length(NEW.emp_name) < 10 OR NEW.emp_name IS NULL THEN
  RAISE EXCEPTION 'The emp_name cannot be less than 10 characters';
    END IF;
    IF NEW.emp_nAME IS NULL THEN
        RAISE EXCEPTION 'emp_name cannot be NULL';
    END IF;
    RETURN NEW;
END;
$$
LANGUAGE plpgsql;

输出量

执行上述命令后,我们将收到以下消息: check_emp_name()函数已成功创建到组织数据库中。

步骤2:建立新的触发器

创建check_emp_name()函数,我们将在employee表上创建一个新触发器以检查员工的emp_name。

每当我们在Employee表中更新或插入一行(取自Organization数据库)时,都将执行相同的触发器:

CREATE TRIGGER emp_name_check 
BEFORE INSERT OR UPDATE
ON employee
FOR EACH ROW 
EXECUTE PROCEDURE check_emp_name();

输出量

实施上述命令后,我们将获得以下消息窗口,该窗口显示emp_name_check触发器已成功插入Employee表。

并且,我们还可以在组织数据库的对象树中验证上面创建的函数(check_emp_name())和触发器(emp_name_check )。

步骤3:放下触发器

成功生成函数和触发器后,我们将在DROP TRIGGER命令的帮助下删除emp_name_check触发器,如下所示:

DROP TRIGGER emp_name_check
ON employee;

输出量

实施上述命令后,我们将获得以下输出,该输出显示特定触发器已成功从Employee表中删除。

总览

PostgreSQL Drop Trigger部分中,我们学习了以下主题:

  • 我们了解PostgreSQL删除触发器命令的用法,该命令用于删除特定表的触发器。