Link:

http://www.essentialsql.com/what-is-a-database-trigger/

Copy...

What is a Database Trigger?

A database trigger is special stored procedure that is run when specific actions occur within a database.  Most triggers are defined to run when changes are made to a table’s data.  Triggers can be defined to run instead of or after DML (Data Manipulation Language) actions such as INSERT, UPDATE, and DELETE.

Triggers help the database designer ensure certain actions, such as maintaining an audit file, are completed regardless of which program or user makes changes to the data.

The programs are called triggers since an event, such as adding a record to a table, fires their execution.

Triggers and their implementations are specific to database vendors.  In this article we’ll focus on Microsoft SQL server; however, the concepts are the same or similar in Oracle and MySQL.

Note: All the examples for this lesson are based on Microsoft SQL Server Management Studio and the AdventureWorks2012 database.  You can get started using these free tools using my Guide Getting Started Using SQL Server

Events

The triggers can occur AFTER or INSTEAD OF a DML action.  Triggers are associated with the database DML actions INSERT, UPDATE, and DELETE.  Triggers are defined to run when these actions are executed on a specific table.

AFTER triggers

Once the DML actions, such as an INSERT completes, the AFTER trigger executes.  Here are some key characteristics of AFTER triggers:

  • After triggers are run after a DML action, such as an INSERT statement and any ensuing referential cascade actions and constraint checks have run.
  • You can’t cancel the database action using an AFTER trigger. This is because the action has already completed.
  • One or more AFTER triggers per action can be defined on a table, but to keep things simple I recommend only defining one.
  • You can’t define AFTER triggers on views.

INSTEAD OF triggers

INSTEAD OF triggers, as their name implies, run in place of the DML action which caused them to fire.  Items to consider when using INSTEAD OF triggers include:

  • An INSTEAD OF trigger overrides the triggering action. If an INSTEAD OF trigger is defined to execute on an INSERT statement, then once the INSERT statement attempt to run, control is immediately passed to the INSTEAD OF trigger.
  • At most, one INSTEAD OF trigger can be defined per action for a table. This makes sense, as if you had to “INSTEAD OF” triggers for an insert, which one should run?

Special Database Objects

Triggers use two special database objects, INSERTED and DELETED, to access rows affected by the database actions.  Within the scope of a trigger the INSERTED and DELETE objects have the same columns as the trigger’s table.

The INSERTED table contains all the new values; whereas, the DELETED table contains old values.  Here is how the tables are used:

  • INSERT – Use the INSERTED table to determine which rows were added to the table.
  • DELETE – Use the DELETED table to see which rows were removed from the table.
  • UPDATE – Use the INSERTED table to inspect the new or updated values and the DELETED table to see the values prior to update.

Definition

A trigger is defined for a specific table and one or more events.  In most database management systems you can only define one trigger per table.

Below is an example trigger from the AdventureWorks2012 database.

You’ll notice the syntax for a trigger is very similar to that of a stored procedure.  In fact, the trigger uses the same language to implement its logic as do stored procedures.  In MS SQL, this is T-SQL; whereas in Oracle it is PL/SQL.

Here are some important parts to a trigger:

  1. The CREATE Statement – It defines which table is associated with the trigger. In addition this statement is used to specify when the trigger executes (e.g. after insert).
  2. The actual program. In the example, this program runs whenever one or more rows are inserted into the WorkOrder table.
  3. Special database objects – Triggers use specially defined databases objects such as INSERTED, or DELETED to access records affected by the database action.
  4. In this example the trigger is using the INSERTED object to gain access to the newly created rows. The INSERT statement is used to table those rows and add them to a history table.

Uses for Triggers

Here are some common uses for triggers:

Complex Auditing

You can use triggers to track changes made to tables.  In our example above, changes made to the WorkOrder table are recorded a TransactionHistory table.

Typically when creating audit trails, you’ll use AFTER triggers.

You may think this is redundant, as many changes are logged in the databases journals, but the logs are meant for database recovery and aren’t easily accessible by user programs.  The TransactionHistory table is easily referenced and can be incorporated into end user reports.

Enforce Business Rules

Triggers can be used to inspect all data before a DML action is performed.  You can use INSTEAD OF triggers to “intercept” the pending DML operation, apply any business rules, and ultimately complete the transaction.

An example business rule may be that a customer status is defined as:

  • Gold – Purchases over $1,000,000 in the past 12 months.
  • Silver – Purchase of $500,000 to $1,000,000 in the past 12 months.
  • Bronze – All other purchase levels.

An INSTEAD OF trigger could be defined to check the customer status each time a customer record is added or modified.  The status check would involve creating a sum of all the customers’ purchases and ensuring the new status corresponds with the sum of the last 12 months of purchases.

Derive Column Values

Triggers can be used to calculate column values.  For instance, for each customer you may wish to maintain a TotalSales column on the customer record.  Of course, for this to remain accurate, it would have to be update every time a sales was made.

This could be done using an AFTER trigger on INSERT, UPDATE, and DELETE statements for the Sales table.

Triggers Are Tricky!

In general, my advice is to avoid using triggers unless absolutely necessary.

You should avoid using triggers in place of built in features.  For instance, rather than rely on triggers to enforce referential integrity, you’re better off using relationships.

Here are some reasons why I shy away from them:

  1. They can be hard to troubleshoot.
  2. Triggers can cause other triggers to fire. Two Tables, A and B, both have an AFTER UPDATE trigger.  If the AFTER UPDATE trigger on Table A updates Table B, then updating Table A causes it’s trigger and then B’s trigger to Fire.
  3. You have to be sure you don’t create a trigger storm! Can you imagine if Table B, for some reason, updated Table A?  Now you have a circular reference…  Boom!
  4. I try to move as much logic into Stored Procedures and have applications make changes to the database through them rather than straight up SQL statements.

What is a Database Trigger?的更多相关文章

  1. Oracle12c中多宿主环境(CDB&PDB)的数据库触发器(Database Trigger)

    Oracle12c中可插拔数据库(PDBs)上的多宿主数据库触发器 随着多宿主选项的引入,数据库事件触发器可以在CDB和PDB范围内创建. 1.   触发器范围 为了在CDB中创建数据库事件触发器,需 ...

  2. [结]Oracle trigger(触发器)摘录

    1.触发器: 是许多关系数据库系统都提供的一项技术.在ORACLE系统里,触发器类似过程和函数,都有声明,执行和异常处理过程的PL/SQL块. 触发器在数据库里以独立的对象存储,它与存储过程和函数不同 ...

  3. ORACLE DB TRIGGER详解

    本篇主要内容如下: 8.1 触发器类型 8.1.1 DML触发器 8.1.2 替代触发器 8.1.3 系统触发器 8.2 创建触发器 8.2.1 触发器触发次序 8.2.2 创建DML触发器 8.2. ...

  4. 使用Server Trigger保护重要的数据库对象

    一 .Server Trigger的简单介绍 在SQL Server数据库中,Server Trigger 是一种特殊类型的存储过程,它可以对特定表.视图或存储中的必然事件自动响应,不由用户调用.创建 ...

  5. 【Oracle】详解ORACLE中的trigger(触发器)

    本篇主要内容如下: 8.1 触发器类型 8.1.1 DML触发器 8.1.2 替代触发器 8.1.3 系统触发器 8.2 创建触发器 8.2.1 触发器触发次序 8.2.2 创建DML触发器 8.2. ...

  6. 16Oracle Database 系统权限和对象权限

    Oracle Database 系统权限和对象权限 Oracle中的系统权限和对象权限 DCL 数据控制语言 -- 查看对象的权限 grant / revoke 查看登录用户 Show user 查看 ...

  7. 从AdventureWorks学习数据库建模——实体分析

    最近打算写写数据库建模的文章,所以打算分析微软官方提供的SQL Server示例数据库AdventureWorks,看看这个数据库中有哪些值得学习的地方. 首先我们需要下载安装一个SQL Server ...

  8. Oracle触发器原理、创建、修改、删除

    本篇主要内容如下: 8.1 触发器类型 8.1.1 DML触发器 8.1.2 替代触发器 8.1.3 系统触发器 8.2 创建触发器 8.2.1 触发器触发次序 8.2.2 创建DML触发器 8.2. ...

  9. linux 安装 ArcSDE10.1

    实验仍未成功,步骤仅供参考. 1:首先检查一下在Linux操作系统下Oracle数据库是否能启动,是否能连通等 [oracle@localhost ~]$ sqlplus SQL*Plus: Rele ...

随机推荐

  1. ngInclude与script加载模板

    ng-include: 官网实例: <p>ng-include:</p> <select ng-model="template" ng-options ...

  2. ARCGIS常用几种本地数据AE初始化

    1.Personal GDB 新建一个在E盘的名为test的mdb: IWorkspaceFactory workspaceFactory = new AccessWorkspaceFactoryCl ...

  3. 第二轮冲刺-Runner站立会议03

    今天做了什么:查看gridview与baseadapter适配器 明天准备做什么:继续gridview与baseadapter适配器 遇到的困难:暂无

  4. (转)为什么所有浏览器的userAgent都带Mozilla

    转自:http://www.eamonning.com/blog/view/289 以下是全文 最早的时候有一个浏览器叫NCSA Mosaic,把自己标称为NCSA_Mosaic/2.0 (Windo ...

  5. 7 款顶级开源 BI(商务智能)软件和报表工具

    在这个信息化时代,每分每秒都产生海量数据.在海量数据中,挖掘出有用的数据,并且能以较人性化.直观的方式展示这些数据,变得尤为重要.本文将介绍 7款顶级开源 BI(商务智能)软件和报表工具,用于商业数据 ...

  6. Spring实战 (第3版)——AOP

    在软件开发中,分布于应用中多处的功能被称为横切关注点.通常,这些横切关注点从概念上是与应用的 业务逻辑相分离的(但是往往直接嵌入到应用的业务逻辑之中).将这些横切关注点与业务逻辑相分离正是 面向切面编 ...

  7. Codeforces #261 D

    Codeforces #261 D D. Pashmak and Parmida's problem time limit per test 3 seconds memory limit per te ...

  8. 关于BigDecimal 和 double 类型保存金钱,以及精度问题,银行家舍入法

    1. BigDecimal 类型数据 的创建,构造函数 有 public BigDecimal(BigInteger intVal, long val, int scale, int prec); p ...

  9. thinkphp3.2.3关于模板使用之一二

    1.包含文件 使用场景:比如我们在编写网页布局的时候,可能每一个网页的头和脚是相同的,此时如果给每一个网页分别设置,未免太麻烦了.此时就可以使用带包含文件. 首先检查配置文件查看我们的主题目录在哪儿, ...

  10. window下安装zookeeper

    本地zookeeper安装(win7)下载zookeeper-3.3.6.zip文件解压zookeeper-3.3.6.zip文件到d:盘在D:\zookeeper-3.3.6\conf下增添 zoo ...