Home Database Mysql Tutorial Oracle触发器(trigger):一般用法

Oracle触发器(trigger):一般用法

Jun 07, 2016 pm 05:30 PM

trigger和procedure,function类似,只不过它不能被显示调用,只能被某个事件触发然后oracle自动去调用.常用的一般是针对一个表或视

trigger和procedure,function类似,只不过它不能被显示调用,只能被某个事件触发然后Oracle自动去调用.常用的一般是针对一个表或视图创建一个trigger,然后对表或视图做某些操作时触发trigger.当然除此之外还有,schema,database级别的trigger.

什么样的操作触发trigger

常见的是DML(insert,update,delete) , DDL(create,alter,drop)语句.

不常见的是schema级别trigger在session连接或断开时触发.database级别trigger在系统启动或退出时触发.

你可能很容易发现如果是select查询操作就没法用到trigger,而有时可能我们想监测谁查看了一些敏感信息,此时只能用到一个叫FGA的东东,可以创建一个审计策略(可以看成加强版的trigger,FGA介绍详见:  ) 

使用触发器注意事项

1.触发器不接受参数,一个表最多可有12个触发器(触发器类型刚好是12种),并且同一时间,同一事件,同一类型的触发器只能有一个(保证触发器操作不冲突嘛).

2.触发器最大为32KB,由于大小受到限制自然也不能使用long,blob这样的大变量.如果实在是有复杂的逻辑,要弄个很复杂的触发器,可以通过procedure或function实现一部分功能,然后调用

3.因为触发器实际上可以看作触发语句的一部分.所以得遵循一些约束条件,比如不能有事务控制语句(commit,rollback,savepoint),DDL语句.为啥子呢,这些特殊语句与一般sql语句的最主要区别是涉及到commit的问题.所以如果触发语句只是一般语句的话自然不能因为trigger的操作带有commit这样的特性了. 

创建触发器

针对表或视图的触发器格式如下: 

CREATE [OR REPLACE] TRIGGER trigger_name

{BEFORE | AFTER }

{INSERT | DELETE | UPDATE [OF column [, column …]]}

[OR {INSERT | DELETE | UPDATE [OF column [, column …]]}...]

ON [schema.]table_name | [schema.]view_name

[REFERENCING {OLD [AS] old | NEW [AS] new| PARENT as parent}]

[FOR EACH ROW ]

[WHEN condition]

PL/SQL_BLOCK | CALL procedure_name;

 

先来看一个简单的,statement级别的trigger怎么创建.假如有表tb1,每insert一点就通过trigger在tblog中记录一些信息.

create or replace trigger tb1_trigger

after insert on tb1

referencing new as new old as old

 

declare

v_info varchar2(100);

begin

v_info := "do a insert";

insert into tblog(info) values(v_info);

end;

 

trigger的创建中有个不太容易理解的内容:一针对row级别的trigger旧值新值问题

row级别trigger旧值新值

针对一个表或视图创建trigger时分为statement级别与row级别的trigger.所谓statement级别是说一个sql语句触发一次trigger,而如果是row级别则一个sql语句涉及到多行数据则trigger会被触发多次.

而旧值就是指要更改的那一行数据在被改之前的值,新值就是用户更新后值.假如表tt只有一列一行数据:88.然后用户执行语句update tt set id = 99 where id = 88;

则旧值指88,新值指99.那你们可能会问用什么方式去得到旧值或新值啊.来举例看下

假如有表tb(eno int); 和表tblog( info varchar2(100)); 假如在tb上创建trigger,tb每update一次则在tblog中记录旧值就更改后的新值.

 

CREATE OR REPLACE TRIGGER tb_trigger

BEFORE UPDATE

ON tb

REFERENCING NEW AS new_val OLD AS old_val --在这里设置名字,然后可引用新值,旧值.如果不指定默认值为new ,old.可以通过:new或:old去引用

FOR EACH ROW

DECLARE

v_info varchar2(100);

BEGIN

 

v_info := 'old value:' ||to_char( :old_val.eno) || 'new value:' || to_char(:new_val.eno);

insert into tblog values(v_info);

END;

条件判断

假如只有在涉及到某一行的操作时触发trigger,假如该触发器是针对updat,delete,insert都触发的情形.咋整呢,自然是多用些when去判断啊.

例如

CREATE OR REPLACE TRIGGER tb_trigger

BEFORE UPDATE or insert or delete

ON tb

REFERENCING NEW AS new_val OLD AS old_val --在这里设置名字,然后可引用新值,旧值

FOR EACH ROW

when (old_val.eno = 99)

DECLARE

v_info varchar2(100);

BEGIN

 

case

when updating then

v_info := 'old value:' ||to_char( :old_val.eno) || 'new value:' || to_char(:new_val.eno);

insert into tblog values(v_info);

 

when inserting then

null;

 

when deleting then

null;

 

end case;

END;

linux

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Hot Topics

Java Tutorial
1655
14
PHP Tutorial
1252
29
C# Tutorial
1226
24
When might a full table scan be faster than using an index in MySQL? When might a full table scan be faster than using an index in MySQL? Apr 09, 2025 am 12:05 AM

Full table scanning may be faster in MySQL than using indexes. Specific cases include: 1) the data volume is small; 2) when the query returns a large amount of data; 3) when the index column is not highly selective; 4) when the complex query. By analyzing query plans, optimizing indexes, avoiding over-index and regularly maintaining tables, you can make the best choices in practical applications.

Can I install mysql on Windows 7 Can I install mysql on Windows 7 Apr 08, 2025 pm 03:21 PM

Yes, MySQL can be installed on Windows 7, and although Microsoft has stopped supporting Windows 7, MySQL is still compatible with it. However, the following points should be noted during the installation process: Download the MySQL installer for Windows. Select the appropriate version of MySQL (community or enterprise). Select the appropriate installation directory and character set during the installation process. Set the root user password and keep it properly. Connect to the database for testing. Note the compatibility and security issues on Windows 7, and it is recommended to upgrade to a supported operating system.

MySQL: Simple Concepts for Easy Learning MySQL: Simple Concepts for Easy Learning Apr 10, 2025 am 09:29 AM

MySQL is an open source relational database management system. 1) Create database and tables: Use the CREATEDATABASE and CREATETABLE commands. 2) Basic operations: INSERT, UPDATE, DELETE and SELECT. 3) Advanced operations: JOIN, subquery and transaction processing. 4) Debugging skills: Check syntax, data type and permissions. 5) Optimization suggestions: Use indexes, avoid SELECT* and use transactions.

Can mysql and mariadb coexist Can mysql and mariadb coexist Apr 08, 2025 pm 02:27 PM

MySQL and MariaDB can coexist, but need to be configured with caution. The key is to allocate different port numbers and data directories to each database, and adjust parameters such as memory allocation and cache size. Connection pooling, application configuration, and version differences also need to be considered and need to be carefully tested and planned to avoid pitfalls. Running two databases simultaneously can cause performance problems in situations where resources are limited.

RDS MySQL integration with Redshift zero ETL RDS MySQL integration with Redshift zero ETL Apr 08, 2025 pm 07:06 PM

Data Integration Simplification: AmazonRDSMySQL and Redshift's zero ETL integration Efficient data integration is at the heart of a data-driven organization. Traditional ETL (extract, convert, load) processes are complex and time-consuming, especially when integrating databases (such as AmazonRDSMySQL) with data warehouses (such as Redshift). However, AWS provides zero ETL integration solutions that have completely changed this situation, providing a simplified, near-real-time solution for data migration from RDSMySQL to Redshift. This article will dive into RDSMySQL zero ETL integration with Redshift, explaining how it works and the advantages it brings to data engineers and developers.

The relationship between mysql user and database The relationship between mysql user and database Apr 08, 2025 pm 07:15 PM

In MySQL database, the relationship between the user and the database is defined by permissions and tables. The user has a username and password to access the database. Permissions are granted through the GRANT command, while the table is created by the CREATE TABLE command. To establish a relationship between a user and a database, you need to create a database, create a user, and then grant permissions.

Laravel Eloquent ORM in Bangla partial model search) Laravel Eloquent ORM in Bangla partial model search) Apr 08, 2025 pm 02:06 PM

LaravelEloquent Model Retrieval: Easily obtaining database data EloquentORM provides a concise and easy-to-understand way to operate the database. This article will introduce various Eloquent model search techniques in detail to help you obtain data from the database efficiently. 1. Get all records. Use the all() method to get all records in the database table: useApp\Models\Post;$posts=Post::all(); This will return a collection. You can access data using foreach loop or other collection methods: foreach($postsas$post){echo$post->

MySQL: The Ease of Data Management for Beginners MySQL: The Ease of Data Management for Beginners Apr 09, 2025 am 12:07 AM

MySQL is suitable for beginners because it is simple to install, powerful and easy to manage data. 1. Simple installation and configuration, suitable for a variety of operating systems. 2. Support basic operations such as creating databases and tables, inserting, querying, updating and deleting data. 3. Provide advanced functions such as JOIN operations and subqueries. 4. Performance can be improved through indexing, query optimization and table partitioning. 5. Support backup, recovery and security measures to ensure data security and consistency.

See all articles