|
所在平台: Udemy |
课程主页: https://www.udemy.com/course/introduction-to-database-triggers-with-postgresql/
课程评论:没有评论
**课程名称:PostgreSQL 数据库触发器入门** **课程概述:** 本课程旨在介绍 PostgreSQL 数据库触发器,这是一种在特定数据库事件(如 INSERT, UPDATE, DELETE, TRUNCATE)发生时自动执行的程序化代码。触发器主要用于维护数据库信息的完整性,例如,当在 `employees` 表中添加新员工记录时,自动在 `taxes`、`vacations` 和 `salaries` 表中创建相应记录。此外,触发器还可用于记录历史数据,例如追踪员工的过往薪资变化。 **核心内容:** * **触发器定义:** 触发器是与表绑定的特殊用户定义函数,会在关联事件发生时自动调用,与普通用户定义函数的主要区别在于其自动执行性。 * **触发器创建流程:** 创建触发器需要先定义一个触发器函数,然后将其绑定到指定的表上。 * **PostgreSQL 触发器类型:** PostgreSQL 提供两种主要的触发器类型: * **行级触发器 (Row-level triggers):** 针对受语句影响的每一行都会被调用一次。例如,如果一个 UPDATE 语句影响了 20 行,行级触发器就会被调用 20 次。 * **语句级触发器 (Statement-level triggers):** 无论语句影响多少行,都只会被调用一次。 * **触发器执行时机:** 可以指定触发器在事件发生 **之前 (BEFORE)** 或 **之后 (AFTER)** 执行。 * **BEFORE 触发器:** 可以在触发器内跳过多行操作,甚至修改将要被更新或插入的行。 * **AFTER 触发器:** 可以访问所有已经完成的更改。
A database trigger is procedural code that is automatically executed in response to certain events on a particular table or view in a database. The trigger is mostly used for maintaining the integrity of the information on the database. For example, when a new record (representing a new worker) is added to the employees table, new records should also be created in the tables of the taxes, vacations and salaries. Triggers can also be used to log historical data, for example to keep track of employees' previous salaries.A PostgreSQL trigger is a function invoked automatically whenever an event associated with a table occurs. An event could be any of the following: INSERT, UPDATE, DELETE or TRUNCATE.A trigger is a special user-defined function that binds to a table. To create a new trigger, you must define a trigger function first, and then bind this trigger function to a table. The difference between a trigger and a user-defined function is that a trigger is automatically invoked when an event occurs.PostgreSQL provides two main types of triggers: row and statement level triggers. The differences between the two are how many times the trigger is invoked and at what time. For example, if you issue an UPDATE statement that affects 20 rows, the row level trigger will be invoked 20 times, while the statement level trigger will be invoked 1 time.You can specify whether the trigger is invoked before or after an event. If the trigger is invoked before an event, it can skip the operation for the current row or even change the row being updated or inserted. In case the trigger is invoked after the event, all changes are available to the trigger.