当前位置:网站首页>Oracle triggers
Oracle triggers
2022-07-28 21:57:00 【Xiao Lei y】
Oracle trigger
1. Trigger Overview
- The essence of trigger is a stored procedure , seeing the name of a thing one thinks of its function , When a specific event occurs Oracle Will execute the code in the trigger ( and java The monitor inside is a little similar );
- Specific events : Is to execute the update DML and DDL sentence ;
- Triggers cannot be explicit ( Manual ) Called ;
- Components of trigger :
- Trigger statements ( event ): Define the... That activates the trigger DML Events and DDL event ;
- Trigger limit (when): Conditions for executing triggers , This condition must be true to activate the trigger ;
- Trigger action ( The main body ): It is the specific event to express after the trigger is triggered , stay begin and end Between sql.
Classification of triggers :
- Divide... In time :After trigger and Before trigger Two kinds of ;
- From the modification of data :insert、delete、update Three ;
- Divide from the scope of application : Row level triggers and table level triggers .
2. How triggers work
After trigger :
Post trigger , That is, after the data of the table is updated , Note that it is not after saving .Before trigger :
Pre trigger , That is, trigger before the data of the table is updated .Trigger before adding operation , The modification and deletion operations are triggered after .
3. A temporary table -:new and :old
When using triggers Oracle The temporary table will be automatically created according to the type of trigger used -:new perhaps :old, The fields in the table are consistent with those in the currently operated table .
A temporary table “:new”: When adding Oracle The temporary table will be automatically created , It is used to temporarily store the added data . After confirming the added data , Then insert the data in the temporary table into the real table . Wait until the add operation is submitted , The temporary table disappears automatically .
A temporary table “:old”: Delete 、 When modifying operations Oracle The temporary table will be automatically created , It is used for temporary storage and deletion 、 Data before modification . Delete, etc 、 After the modification operation is submitted , The temporary table disappears automatically .
4. Create trigger Syntax
create or replace trigger Trigger Name -- Trigger Name
after insert -- Post trigger , And it is to add type trigger
on Table name -- The table on which the trigger depends
for each row -- Line level triggers
begin
if :new. Field = 0 then -- Trigger conditions
dbms_output.put_line(' Warning : Record inserted , But the quantity is zero ');
raise_application_error(-20018,' Warning : Record inserted , But the quantity is zero !'); -- Throw an exception ,-20018 It's an error code , The scope is -20000 To -21000.
end if;
end;
5 trigger
5.1 Data script
-- Create a student information table
create table stuInfo
(
stuNo varchar2(8) not null primary key,
stuName varchar2(10) not null,
stuSex varchar2(2) not null,
stuAge number(6) not null,
stuSeat number(6) not null,
strAddress varchar2(255) default(' The address is unknown ')
)
-- Create a student transcript
create table stuMarks
(
ExamNo varchar2(7) not null primary key,
stuNo varchar2(6) not null references stuInfo(stuNo),
writtenExam number(6) null,
LabExam number(6) null
)
-- Insert test data into the student information table
insert into stuInfo(stuNo, stuName, stuSex, stuAge,stuSeat,strAddress)
select 's25301', ' Zhang Qiuli ', ' male ', 18,1, ' Beijing haidian ' from dual union
select 's25303', ' Lisbon ', ' Woman ', 22,2, ' Heyang Luoyang ' from dual union
select 's25302', ' Li Wencai ', ' male ', 85, 3,' The address is unknown ' from dual union
select 's25304', ' Ouyang Junxiong ', ' male ', 28, 4,' xinjiang ' from dual union
select 's25318', ' Mei Chaofeng ', ' Woman ', 23, 5,' The address is unknown ' from dual
insert into stuInfo(stuNo, stuName, stuSex, stuAge,stuSeat,strAddress)
select 's25322', ' Publicize a', ' male ', 18,1, ' Beijing haidian ' from dual
-- Insert test data into the student transcript
insert into stuMarks(ExamNo, stuNo, writtenExam, LabExam)
select 's271811', 's25303', 93, 59 from dual union
select 's271813', 's25302', 63, 91 from dual union
select 's271816', 's25301', 90, 83 from dual union
select 's271817', 's25318', 63, 53 from dual
select * from stuinfo;
select * from stumarks;
5.2 Post trigger -delete operation
-- Lisiwen cannot be deleted .
create or replace trigger tname -- Trigger Name
after delete -- Then trigger ( Delete class )
on stuinfo -- Table name
for each row -- Line level triggers
begin
-- From the old watch (:old) Get the name of the deleted student and judge
if :old.stuname=' Lisbon ' then
raise_application_error(-20018,' This student cannot be deleted !'); -- Throw an exception
end if;
end;
5.3 Pre trigger insert& Post trigger delete& Post trigger &update
-- Liswen cannot be deleted , Zhang San cannot add , Mei Chaofeng cannot modify .
create or replace trigger tname
after delete or insert or update
on stuinfo
for each row
begin
if deleting then-- Delete
-- From the old watch (:old) Get the name of the deleted student and judge
if :old.stuname=' Lisbon 'then
raise_application_error(-20018,' This student cannot be deleted !');
end if;
elsif inserting then-- increase
-- From the new table (:new) Get the names of the added students and make judgments
if :new.stuname=' Zhang San ' then
raise_application_error(-20019,' The student cannot !');
end if;
elsif updating then-- modify
-- From the old watch (:old) Get the name of the student to be modified and judge
if :old.stuname=' Mei Chaofeng ' then
raise_application_error(-20020,' This student cannot modify !');
end if;
end if;
end;
5.4 Multi table deletion
-- Delete students and automatically delete their grades .
create or replace trigger tname
after delete
on stuinfo
for each row
declare -- Define variables to save the student ID to be deleted ( It is also possible not to define )
sno varchar2(10);
begin
-- Get the student ID of the deleted student
sno:=:old.stuno;
delete from stumarks where stuno=:old.stuno; --( Or write stuno=sno)
end;
5.4 trigger + Sequence = Identity column
create sequence sname_01; -- Create sequence
-- Create trigger
create or replace trigger tname
before insert
on Table name
for each row
begin
:new.sid:=sname_01.nextval;
end;
6. Case study
select * from stuinfo;
select * from stumarks;
--1、 In the student information form stuinfo Set trigger on : Liswen cannot be deleted ;
create or replace trigger a_1
after delete
on stuinfo
for each row
begin
if:old.stuname=' Lisbon ' then
raise_application_error(-20018,' Liswen cannot be deleted ');
end if;
end;
delete from stuinfo where stuname=' Lisbon ';
--2、 In the student information form stuinfo Set trigger on : Fools cannot increase ;
create or replace trigger a_2
after insert
on stuinfo
for each row
begin
if:new.stuname=' Idiot 'then
raise_application_error(-20019,' Fools cannot increase ');
end if;
end;
insert into stuinfo values('s25324',' Idiot ',' male ',18,20,' Hunan changsha ');
--3、 In the student information form stuinfo Set trigger on : Li Wencai cannot modify ;
create or replace trigger a_3
after update
on stuinfo
for each row
begin
if:old.stuname=' Li Wencai 'then
raise_application_error(-20020,' Li Wencai cannot be modified ');
end if;
end;
update stuinfo set stuname=' Li doubi ' where stuname=' Li Wencai ';
--4、 Create a new item table ( Field customization ), Set the trigger to realize the automatic growth of commodity number .
create table zdy(
sid number,
sname varchar2(10)
)
-- Create sequence
create sequence sid_1
-- Create trigger
create trigger t_4
before insert
on zdy
for each row
begin
:new.sid:=sid_1.nextval;
end;
-- increase
insert into zdy(sname)
values(' Li Si ')
select * from zdy
7. summary
- Triggers are stored procedures that are executed automatically when a specific event occurs
- Triggers are divided into dml trigger 、ddl There are three types of triggers and database level triggers
- dml The three types of triggers include row level triggers 、 Statement level triggers and instead of trigger
- Some commonly used built-in packages :
- dbms_output Package output pl/sql Debugging information of the program
- dbms_lob Packages provide operations lob Subroutine of data
- dbms_xmlquery Convert query results to xml Format
- dbms_random Provide random number generator
- utl_file Used to read and write operating system text files
边栏推荐
- Research on weapon equipment attribute extraction based on attribute word completion
- Matlab | basic knowledge summary I
- 纳米金偶联抗体/蛋白试剂盒(20nm,1mg/100μg/500 μg偶联量)的制备
- Save 70% of the video memory and increase the training speed by 2 times! Zheda & Ali proposed online convolution re parameterization orepa, and the code has been open source! (CVPR 2022 )
- Mesh data generation function meshgrid
- It is said that Microsoft has obtained the supply license for Xianghua! Will Huawei usher in the full lifting of the ban?
- 如何优雅的设计工作流引擎(荣耀典藏版)
- Pytoch learning record (III): random gradient descent, neural network and full connection
- Meeting notice of OA project (Query & whether to attend the meeting & feedback details)
- Research on the recognition method of move function information of scientific paper abstract based on paragraph Bert CRF
猜你喜欢

kingbase中指定用户默认查找schema,或曰用户无法使用public schema下函数问题

Zhuzhou Jiufang middle school carried out drowning prevention and fire safety education and training activities

Knowledge description framework of foreign patent documents based on knowledge elements

Matlab from introduction to mastery Chapter 1 Introduction to matlab

Is it necessary to calibrate the fluke dtx-1800 test accuracy?

For the first time, Chinese scientists used DNA to construct convolutional artificial neural network, which can complete 32 types of molecular pattern recognition tasks, or be used for biomarker signa

Storage and steps of phospholipid coupled antibody / protein Kit
![[极客大挑战 2019]Secret File&文件包含常用伪协议以及姿势](/img/aa/a169cdd8cc6cdfda6d2777511b4dd2.png)
[极客大挑战 2019]Secret File&文件包含常用伪协议以及姿势

Msfvenom makes master and controlled terminals

How many tips do you know about using mock technology to help improve test efficiency?
随机推荐
比UUID更快更安全NanoID到底是怎么实现的?(荣耀典藏版)
管理区解耦架构见过吗?能帮客户搞定大难题的
How is nanoid faster and more secure than UUID implemented? (glory Collection Edition)
Matlab from introduction to mastery Chapter 1 Introduction to matlab
使用Mock技术帮助提升测试效率的小tips,你知道几个?
ST法国三座工厂大罢工,芯片缺货情况或将更加严重!
Query Oracle view creation statement and how to insert data into the view [easy to understand]
NTP server time (view server time)
Object based real-time spatial audio rendering - Dev for dev column
Chinese patent keyword extraction based on LSTM and logistic regression
The Swedish court lifted the 5g spectrum auction ban on Huawei and ZTE
Knowledge description framework of foreign patent documents based on knowledge elements
中国科学家首次用DNA构造卷积人工神经网络,可完成32类分子模式识别任务,或用于生物标志物信号分析和诊断
How to search images efficiently and accurately? Look at the lightweight visual pre training model
Modify the port number of MySQL (is there a problem modifying the port number of MySQL)
标准C语言学习总结10
OA项目之会议通知(查询&是否参会&反馈详情)
系统分析师
Research on intangible cultural heritage image classification based on multimodal fusion
Rhcsa first day