什么是存储过程?什么是触发器?SQL中存储过程与触发器的区别是什么?

存储过程是在大型数据库系统中,一组为了完成特定功能的SQL 语句集,它存储在数据库中,一次编译后永久有效,用户通过指定存储过程的名字并给出参数(如果该存储过程带有参数)来执行它。存储过程是数据库中的一个重要对象。

数据库存储过程的实质就是部署在数据库端的一组定义代码以及SQL。将常用的或很复杂的工作,预先用SQL语句写好并用一个指定的名称存储起来,那么以后要叫数据库提供与已定义好的存储过程的功能相同的服务时,只需调用execute,即可自动完成命令。

每个参数名前要有一个“@”符号,每一个存储过程的参数仅为该程序内部使用,参数的类型除了IMAGE外,其他SQL Server所支持的数据类型都可使用。

SQL中存储过程优点:

1、重复使用。存储过程可以重复使用,从而可以减少数据库开发人员的工作量。

2、减少网络流量。存储过程位于服务器上,调用的时候只需要传递存储过程的名称以及参数就可以了,因此降低了网络传输的数据量。

3、安全性。参数化的存储过程可以防止SQL注入式攻击,而且可以将Grant、Deny以及Revoke权限应用于存储过程。

4、存储过程只在创造时进行编译,以后每次执行存储过程都不需再重新编译,而一般SQL语句每执行一次就编译一次,所以使用存储过程可提高数据库执行速度。

触发器相当于是一个时间的触发装置,当满足了触发事件的条件后进行相应的处理操作,例如在数据库表中增加或者删除、修改了某条记录后,输出消息来告知该操作。这样就可以在这个表上设置一个触发器,触发条件为增加,删除或者修改了记录,触发的时间就是进行消息通知的输出。

那么我们接下来用一种专业的描述来讲解:

1.触发器的作用:触发器是一种程序模块,是数据库的一种自动处理机制。触发器主要作用是保证数据库的安全性,例如:触发器通常通过对操作的记录来对象数据库进行操作的审查,或者实现复杂的约束条件。

2.什么时候用触发器:

根据触发器的触发条件可以分为3中触发器:分别为dml触发器、instead of触发器、ddl触发器。触发器的调用方式不同于存储过程和函数,他是通过“事假”来激活的。所谓的事件,就是数据库的动作或者用户的操作。触发器不能由用户显示调用,而是只能通过当触发事假发生并被扑捉到时,才会被触发。

3.创建触发器的步骤:

创建触发器首先需要create trigger权限

触发器有3中类型:dml触发器、instead of触发器、ddl触发器。在创建语句大致可以分为4步:

  1. 定义触发器
  2. 触发条件(区分不同的触发器的类型)
  3. 声明部分
  4. 主体部分

4.触发器里面是否可以有commit:不能

5.为什么触发器中不能由commit:

因为在Oracle规定,触发器中不能进行任何事务操作,任何对被触发的表进行的操作的事务都会失败,所以触发器中不能由commit

触发器与存储过程非常相似,触发器也是SQL语句集,两者唯一的区别是触发器不能用EXECUTE语句调用,而是在用户执行Transact-SQL语句时自动触发(激活)执行。

触发器是在一个修改了指定表中的数据时执行的存储过程。

通常通过创建触发器来强制实现不同表中的逻辑相关数据的引用完整性和一致性。由于用户不能绕过触发器,所以可以用它来强制实施复杂的业务规则,以确保数据的完整性。

触发器不同于存储过程,触发器主要是通过事件执行触发而被执行的,而存储过程可以通过存储过程名称名字而直接调用。当对某一表进行诸如UPDATE、INSERT、DELETE这些操作时,SQLSERVER就会自动执行触发器所定义的SQL语句,从而确保对数据的处理必须符合这些SQL语句所定义的规则。

A stored procedure (also termed procstorpsprocStoProStoredProcStoreProcspor SPis a subroutine available to applications that access a relational database management system (RDBMS). Such procedures are stored in the database data dictionary.

Stored procedures are a pieces of the code in written in PL/SQL to do some specific task. Stored procedures can be invoked explicitly by the user. It's like a java program , it can take some input as a parameter then can do some processing and can return values.

On the other hand,  trigger is a stored procedure that runs automatically when various events happen (eg update, insert, delete). Triggers are more like an event handler they run at the specific event. Trigger can not take input and they can’t return values.

Sr. No. Key Triggers Stored procedures

1

Basic

trigger is a stored procedure that runs automatically when various events happen (eg update, insert, delete)

Stored procedures are a pieces of the code in written in PL/SQL to do some specific task

2

Running Methodology

It can execute automatically based on the events

It can be invoked explicitly by the user

3

Parameter

It can not take input as parameter

It can take input as a parameter

4

Transaction statements

we can't use transaction statements inside a trigger

We can use transaction statements like begin transaction, commit transaction, and rollback inside a stored procedure

5

Return

Triggers can not return values

Stored procedures can return values


A trigger is a piece of code executed automatically in response to a specific event occurred on a table in the database.

A trigger is always associated with a particular table. If the table is deleted, all the associated triggers are also deleted automatically.

A trigger is invoked either before or after the following event:

  • INSERT – when a new row is inserted
  • UPDATE – when an existing row is updated
  • DELETE – when a row is deleted.

When you issue an INSERTUPDATE, or DELETE statement, the relational database management system (RDBMS) fires the corresponding trigger.

In some RDMBS, a trigger is also invoked in the result of executing a statement that calls the INSERTUPDATE, or DELETE statement. For example, MySQL has the LOAD DATA INFILE, which reads rows from a text file and inserts into a table at a very high speed, invokes the BEFORE INSERT and AFTER INSERT triggers.

On the other hand, a statement may delete rows in a table but does not invoke the associated triggers. For example, TRUNCATE TABLE statement removes all rows in the table but does not invoke the BEFORE DELETE and AFTER DELETE triggers.

Trigger creation statement syntax

To create a trigger, you use the following statement:

 

CREATE TRIGGER trigger_name [BEFORE|AFTER] event ON table_name trigger_type BEGIN -- trigger_logic END;

Code language: SQL (Structured Query Language) (sql)

Let’s examine the syntax in more detail:

  • First, specify the name of the trigger after the CREATE TRIGGER clause.
  • Next, use either BEFORE or AFTER keyword to determine when to the trigger should occur in response to a specific event e.g., INSERTUPDATE, or DELETE.
  • Then, specify the name of the table to which the trigger binds.
  • After, specify the type of trigger using either FOR EACH ROW or FOR EACH STATEMENT. We will discuss more on this in the next section.
  • Finally, put the logic of the trigger in the BEGIN ... END block.

Besides using the code in the BEGIN END block, you can execute a stored procedure as follows:

 

CREATE TRIGGER trigger_name [BEFORE|AFTER] event ON table_name trigger_type EXECUTE stored_procedure_name;

Code language: SQL (Structured Query Language) (sql)

Row level trigger vs. statement level trigger

There are two types of triggers: row and statement level triggers.

A row level trigger executes each time a row is affected by an UPDATE statement. If the UPDATE statement affects 10 rows, the row level trigger would execute 10 times, each time per row. If the UPDATE statement does not affect any row, the row level trigger is not executed at all.

Different from the row level trigger, a statement level trigger is called once regardless of how many rows affect by the UPDATE statement. Note that if the UPDATE statement did not affect any rows, the trigger will still be executed.

When creating a trigger, you can specify whether a trigger is row or statement level by using the FOR EACH ROW or FOR EACH STATEMENTrespectively.

SQL trigger usages

You typically use the triggers in the following scenarios:

  • Log table modifications. Some tables have sensitive data such as customer email, employee salary, etc., that you want to log all the changes. In this case, you can create the UPDATE trigger to insert the changes into a separate table.
  • Enforce complex integrity of data. In this scenario, you may define triggers to validate the data and reformat the data if necessary. For example, you can transform the data before insert or update using a BEFORE INSERT or BEFORE UPDATE trigger.

SQL trigger example

We will use the employees table in the sample database for the demonstration.

Suppose we want to log the changes of values in the salary column. To do this, we create a separate table for storing the changes and use a trigger to insert the changes into this table.

The following statement creates the salary_changes table.

 

CREATE TABLE salary_changes ( employee_id INT, changed_at DATETIME DEFAULT CURRENT_TIMESTAMP, old_salary DECIMAL(8 , 2 ), new_salary DECIMAL(8 , 2 ), PRIMARY KEY (employee_id , changed_at) );

Code language: SQL (Structured Query Language) (sql)

The salary_changes table logs the employee id, old salary, new salary and the time of changes. Note that the change_at column uses the current time as the default to log the time when the change occurs.

The following before_update_salary trigger logs the salary changes to the salary_changes table.

 

CREATE TRIGGER before_update_salary BEFORE UPDATE ON employees FOR EACH ROW BEGIN IF NEW.salary <> OLD.salary THEN INSERT INTO salary_changes(employee_id,old_salary,new_salary) VALUES(NEW.employee_id,OLD.salary,NEW.salary); END IF; END;

Code language: SQL (Structured Query Language) (sql)

In the body of the trigger, we insert the changes if the new salary is different from the old one.

Note that within the trigger body, we use the OLD and NEW keywords to access columns in the rows affected by a trigger.

Let’s test the trigger by raising the salary of the employee whose id is 102 5%.

First, check the current salary of the employee 102:

 

SELECT employee_id, first_name, last_name, salary FROM employees WHERE employee_id = 110;

Code language: SQL (Structured Query Language) (sql)

Second, raise the salary by 5% by issuing the following UPDATE statement.

 

UPDATE employees SET salary = salary * 1.05 WHERE employee_id = 110;

Code language: SQL (Structured Query Language) (sql)

Third, check the salary_changes table to see if the trigger has been invoked.

 

SELECT * FROM salary_changes;

Code language: SQL (Structured Query Language) (sql)

As you see, the salary_changes table has a new entry. It means that the trigger has been invoked correctly.

Modify triggers

To change the trigger definition, you use the  CREATE OR REPLACE TRIGGER statement.

Basically, the CREATE OR REPLACE TRIGGER creates a new trigger if it does not exist and changes the trigger if it does exist.

The CREATE OR REPLACE TRIGGER statement is similar to the CREATE TRIGGER statement as follows:

 

CREATE OR REPLACE TRIGGER trigger_name [BEFORE|AFTER] event ON table_name trigger_type BEGIN -- trigger_logic END;

Code language: SQL (Structured Query Language) (sql)

Delete triggers

To delete a trigger, you use the DROP TRIGGER statement as follows:

 

DROP TRIGGER [IF EXISTS] trigger_name;

Code language: SQL (Structured Query Language) (sql)

The IF EXISTS option allows you to delete a trigger if the trigger exists. If the trigger does not exist, then the statement does nothing.  However, if you don’t have the IF EXISTS option, the database system may issue an error if you try to drop a non-existing trigger.

Again, if you drop a table, all triggers associated with the table are also deleted. The following statement deletes the before_update_salary trigger:

 

DROP TRIGGER IF EXISTS before_update_salary;

Code language: SQL (Structured Query Language) (sql)

Now you should have a good understanding of the SQL triggers and know how to create a trigger in the database system.

参考:SQL中的触发器是什么?

参考:sql stored procedure and trigger

参考:Difference between stored procedure and triggers in SQL

参考:Introduction to SQL Triggers

什么是存储过程?什么是触发器?SQL中存储过程与触发器的区别是什么?相关推荐

  1. Sql中存储过程的定义、修改和删除操作

    Sql中存储过程的定义.修改和删除操作 1.存储过程的分类 系统存储过程 本地存储过程(用户自定义) 临时存储过程(局部[#].全局[##]临时存储过程) 2.创建存储过程 ? 1 2 3 4 5 6 ...

  2. PL/SQL中存储过程int和out的用法

    PL/SQL中存储过程int和out的用法 一 介绍 过程和函数中的in和out (1)一般来讲,过程和函数的区别在于函数可以有一个返回值:而过程没有返回值. (2)但过程和函数都可以通过out指定一 ...

  3. db2 删除存储过程_数据库教程-SQL Server存储过程使用及异常处理

    SQL Server存储过程 存储过程(Procedure)是数据库重要对象之一,也是数据库学习的重点之一.本文,我们以SQL Server为例对存储过程的概念.定义.调用.删除及存储过程调用异常等通 ...

  4. mysql启动触发器_MYSQL中禁用/启动触发器

    在使用MYSQL过程中,经常会使用到触发器,但是有时使用不当会造成一些麻烦.有没有一种办法可以控制触发器的调用呢? 触发器顾名思义就是数据库在一定的调条件自动调用的SQL语句,触发器拒绝了人工调用的过 ...

  5. 浅谈SQL中存储过程和自定义函数的区

    存储过程: 存储过程可以使得对数据库的管理.以及显示关于数据库及其用户信息的工作容易得多.存储过程是 SQL 语句和可选控制流语句的预编译集合,以一个名称存储并作为一个单元处理.存储过程存储在数据库内 ...

  6. 【学习记录】Sql中存储过程的

    存储过程中@@ROWCOUNT SQL的系统变量@@ROWCOUNT返回的是上一语句影响的行数. WHILE(@@ROWCOUNT > 0)             BEGIN          ...

  7. sql中存储过程打印返回的记录集

    declare --返回结果,记录类型 ret sys_refcursor;--定义一种类型,用来存放返回的记录type typ_row is record ( SPNRID varchar2(100 ...

  8. SQL中存储过程和函数的标准写法

    之前一直用的存储过程,今天忽然又接触到跑算法获取返回值的问题,想到可以用函数,好久没用过一时忘了怎么写,还要现查,于是就记录下来,顺便连存储过程一块啦. 存储过程: CREATE PROC dbo.存 ...

  9. mysql 触发器 sql日志_sql update 触发器 可获得被update的行的信息

    SQL Server 2005 学习笔记之触发器简介[转] 触发器实际上就是一种特殊类型的存储过程,其特殊性表现在:它是在执行某些特定的T-SQL语句时自动的. 11.1 触发器简介 触发器实际上就是 ...

最新文章

  1. 当你累了,准备放弃时,看看这个吧!!!
  2. requestAnimationFrame,Web中写动画的另一种选择
  3. Kafka实战-Flume到Kafka
  4. leetcode算法题--二叉树中序遍历迭代法
  5. linux端口监听命令
  6. Linux7如何手动建库,Centos 7系列删除数据库并重新安装
  7. 2008春节长白山哈尔滨雪乡游
  8. Ubuntu+Django+Nginx+uWSGI+Mysql搭建Python Web服务器
  9. 企业实战_07_MyCat 搭建Mysql 一主一从复制环境
  10. JCG新年献礼,JHR-N825R给力上市
  11. What is an Operating System?
  12. Zmail-简单易用的python邮件模块
  13. [msi]启动msi日志记录
  14. 机器学习中的距离/散度/熵
  15. DIY_实现光敏电阻传感器简单控制LED
  16. 中科院计算机和理论物理双硕士白,中科院研究生理论物理怎么不学相对论?
  17. 微信终于要对聊天记录动手了?
  18. 连接Charles后,手机无法上网
  19. oracle清空实例数据,Linux下删除oracle实例
  20. 工作积累10——推荐一本看过最好的数据分析的书

热门文章

  1. lpi linux认证权威指南 pdf,LPI Linux认证指南读书笔记
  2. C#用Tesseract进行OCR识别,可识别中英日韩所有语言
  3. 南加大提出NeROIC:还有什么不能渲染的?重建效果太强悍了
  4. ICCV 2021 Oral | 清华提出PoinTr:几何敏感的点云补全Transformer
  5. 自动驾驶激光雷达物体检测技术
  6. Science | 以功能为核心的蛋白质设计
  7. 第十二课.统计推断的基本思想
  8. C语言接收一个整数划分成5的倍数,整数划分为连续整数;整数划分
  9. vue 父页面中的方法 调用_解决Vue中页面成功渲染数据undefined的问题
  10. djaogo知识点 python_python Django知识点总结