当前位置:网站首页>Triggers & built-in packages
Triggers & built-in packages
2022-06-13 03:37:00 【Mouth strong programmer】
========================================================
1. trigger ( The principle of trigger should be explained clearly )
2. Built in packages
One 、 trigger
1. Three operations : delete update insert
2. Two temporary tables : :new :old
3. Two time points : after before
4. Two important models : Row level Sentence level
5. Conditions : when
Oracle Trigger ratio in SQL Server To be complex ;
SQL Server Only one event will be triggered by adding, deleting and modifying in , But in Oracle Two events will be triggered in .
With delete For example ,Oracle There is a pre deletion event before 、 Event after deletion after.
Oracle Trigger points : Pre trigger 、 Post trigger
1. What is trigger ?
(1) Trigger is a special stored procedure ;
(2) Triggers cannot be called directly , It's not a manual start , It's triggered by events ;-- Additions and deletions
(3) Triggers are often used to enforce data integrity constraints and business rules .
(4) Trigger has the function of transaction .
To put it simply : A trigger is a switch , Be responsible for the light on and off , It lights up when you move it .
Oracle Trigger ratio SQL Server It's more complicated , Before triggering before And after triggering after.
2. Create trigger Syntax ( The hardest thing in history oracle grammar , Not one of them. )
create [or replace] trigger trigger_name
after|before|instead of --instead reverse
[insert][[or] update [of Column list ]][[or] delete]
on table Table or view -- View usage
[referencing{:old [as] old/:new [as] new}] -- Quote the new table and the old table
[for each row] -- Row level mode
[when(condition)] -- Conditions
pl/sql_block; --pl/sql sentence (begin...end)
insert after before
-- Case study :
insert into emp values(…, Zhang San ,…,0,……);
==> Go to :new
create or replace trigger trig_name
after insert
on emp
for each row
begin
if(:new.sal=0) then
dbms_output.put_line(' Warning : You can't work without pay ');
else
dbms_output.put_line(' Record inserted ');
end if;
end;
3. The trigger consists of three parts :
a. Trigger statements ( event )-- Define the... That activates the trigger DML Events and DDL event ;
b. Trigger limit --- Conditions for executing triggers , This condition is true to activate the trigger ;
c. Trigger action ( The main body )-- contain SQL Statements and code , They run only when the trigger statement is issued and the value of the trigger limit is true .
Notes : The sequence is saved to the database through the pre trigger .
4. Schematic diagram of front trigger and back touch
5. Create trigger cases in cascading tables
-- Liswen cannot be deleted
( When to trigger ?a.delete when ; b.when When conditions are met ; c. The code states )
create or replace trigger t_studel
after delete
on stuinfo
for each row
begin
if :old.stuname=' Lisbon ' then
-- Throw an exception
raise_application_error(-20010,' The student cannot delete !!!');
end if;
end;
delete from emp;
-- Liswen cannot be deleted , Can't change
after delete or update
-- How to know is (insert\delete\update) Which operation ?
……
begin
case
when deleting then
-- deleted
if :old.stuname=' Lisbon ' then
raise_application_error(-20010,' The student cannot delete !!!');
end if;
when updating then
-- When modifying
if :old.stuname=' Lisbon ' then
raise_application_error(-20011,' This student cannot modify !!!');
end if;
when inserting then
-- Insertion time
if :old.stuname=' Zhang Yang ' then
raise_application_error(-20012,' How dare you recruit this student !!!');
end if;
end case;
end;
insert Li Chao :new
insert before ----> if (:old Li Chao ---> Insert into the table == useless
if (:new Li Chao ---> Not inserted into the table
before--->:new
insert after ----> if (:old Li Chao ) ---> Insert into the table
if (:new Li Chao ) ---> Not inserted into the table
before | after insert ----> :new
before | after delete ----> :old
====================================
reflection :
A table can create several insert\update\delete trigger ?
====================================
Trigger of advanced point
-- And mirror pairs
1. Determine on which table the trigger is written on table
2. Determine which trigger to use insert delete update
3. use after still before, use :new :old
-- stay stuinfo Write a in the table delete trigger , Specify the name of the person to delete ,
Delete directly stumarks The score of the person in the table .
create or replace tirgger t_mydel
after delete
on stuinfo
for each row
declare
stu varchar2(22);
begin
stu:=:old.stuno; -- Assign the student ID of the deleted student to the variable
delete from stumarks where stuno=stu;
end;
-- Under operation
delete from stuinfo where stuname=' Lisbon ';
============================================
Be careful :
Triggers for table joins are complex , Yes A Table operation triggers A Trigger for table , At the same time, the shadow arrived B Table triggers B Trigger for table , And so on ...
Suggest : When tables are frequently associated with tables , It is recommended to use triggers .
============================================
Row level triggers and statement level triggers :
-- Case study 2
create or replace tirgger t_mydel
after delete
on stuinfo
for each row
begin
dbms_output.put_line(' Well deleted !');
end;
-- perform ( Deleted a record , The result shows a ' Well deleted ')
delete from stuinfo where stuname=' Li Wencai ';
-- perform ( Deleted records in the entire table , Show N strip ' Well deleted ')
delete from stuinfo
-- explain : This is how to explain row level triggers .
-- Line level triggers : Delete one by one , Deleting an entry triggers a row level trigger .
*********************************
reflection :
If you will [for each row] Code deletion , Execute to see the effect .-- Statement level triggers .
*********************************
-- Statement level triggers : Execute a trigger once .
===========================================
Identity column : Sequence + trigger
-- Create a new table , Ready to insert records , Use triggers and sequences .
create table tb_715(
sid number,
sname varchar2(22)
)
-- Perform the insert operation
insert into tb_715(sid,sname) values(1,' Liu Shuai ')
-- demand : Don't write sid,1 Can help me automatically generate a sequence .
-- solve :(1) Create sequence
create sequence seq715;
(2) Create a trigger , Trigger before use , use new surface
create or replace trigger t_insert
before insert
on tb_715
for each row
begin
-- In the new table id= The next value of the sequence
select seq715.nextval into :new.sid from dual;
end;
*****************************************
oracle 11g The grammar of :
:new.sid:=seq715.nextval;
oracle 10g The grammar of :
select seq715.nextval into :new.sid from dual;
Don't use variables , The method of using variables is 11g Writing .
*****************************************
--:new surface , Put the inserted data into :new In the table , Confirm and put it in the table to be updated .
--:old surface , Put unwanted data into :old In the table , Confirm not to clear :old surface .
-- Be careful ::new Table and :old There is only one piece of data in the table from beginning to end , How many columns are there ? How many columns does the trigger's table have ,:new Table and :old How many columns does the table have .
commit;-- Submit
--oracle-06 trigger
1. Trigger keywords :trigger
2. Trigger Overview : Is a special stored procedure , The stored procedure is a special function
3. effect : When executed DML(insert,update,delete) When the sentence is , The trigger will be triggered automatically , Cannot call manually
4. Usage scenario of trigger :
#(1) You can limit the insertion of data
#(2) You can limit the modification of data
#(3) You can restrict the deletion of data
#(4) a key :a. cascading deletion b. Sequence + trigger ===》 Simulate self growth
5. The syntax of triggers (2322)
# 2: 2 Trigger time points :after|before
# 3: 3 A trigger event insert update delete
# 2: 2 A trigger mode Statement level trigger mode Row level trigger mode (for each row)
# 2: 2 Pseudo table :new :old
create or replace trigger Trigger Name
before|after
insert| update|delete
on tableName
for each row
begin
-- Executable modules : Limit data
end;
--------------------------------------------------------------------
-- 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 ')
)
go
-- 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 ')
)
go
-- 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
)
go
-- 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
go
-- 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
go
select * from stuInfo;
select * from stuMarks;
-- demand : Create a trigger , Restrict students : Kangkang forbids inserting
create or replace trigger t_demo1
after
insert
on stuInfo
for each row
begin
-- Restrict Kangkang from inserting
if (:new.stuName = ' Kang Kang ') then
-- Error window prompt , prevent DML Statement runs successfully .raise_application_error( Status code , error message ); Status code range : -20000 -20099
raise_application_error('-20001',' Kangkang can't insert , There's a stain ');
end if;
end;
insert into stuInfo
select 's25366', ' Kang Kang 2', ' male ', 18,1, ' Beijing haidian ' from dual;
select * from stuInfo;
rollback;
-- Kang Kang 2 Can't delete
create or replace trigger t_demo2
after
delete
on stuInfo
for each row
begin
if(:old.stuName = ' Kang Kang 2') then
raise_application_error('-20002',' Kang Kang 2 Can't delete ');
end if;
end;
delete from stuInfo where stuName = ' Kang Kang 2';
-- demand : To write 1 Trigger , At the same time limit Kang Kang 2 Can't delete , Mei Chaofeng cannot modify , Liaojiajun can't add
create or replace trigger t_demo3
after
insert or update or delete
on stuInfo
for each row
begin
-- A trigger contains multiple limit actions , First judge Which one triggered ?
if inserting then
if (:new.stuName = ' Liaojiajun ') then
raise_application_error('-20004',' Liaojiajun cannot add ');
end if;
elsif deleting then
if (:old.stuName = ' Kang Kang 2') then
raise_application_error('-20005',' Kang Kang 2 Can't delete ');
end if;
elsif updating then
if (:old.stuName = ' Mei Chaofeng ') then
raise_application_error('-20006',' Mei Chaofeng cannot modify ');
end if;
end if;
end;
----------------------------------------------------------------
insert into stuInfo
select 's25333', ' Liaojiajun ', ' male ', 18,1, ' Beijing haidian ' from dual;
-- function : cascading deletion
select * from stuInfo;
select * from stuMarks;
delete from stuInfo where stuName = ' Zhang Qiuli ';
-- When deleting the data of the main table with a trigger , At the same time, delete the data from the table
create or replace trigger t_demo4
after
delete
on Stuinfo
for each row
begin
-- When the trigger is triggered , Get the table where the trigger is located immediately id Delete data from the table as a condition
delete from stuMarks where stuMarks.Stuno = :old.stuno;
end;
-- Sequence + trigger Analog identification column
drop table new_emp;
create table new_emp
as
select empno,ename,sal from emp where 1= 0;
select * from new_emp;
-- Sequence
create sequence s_emp;
-- trigger
create or replace trigger t_emp
before
insert
on new_emp
for each row
begin
-- When the trigger is triggered , Get the next value of the current sequence and assign it to new_emp In the new table id attribute
--oracle 10g
--select s_emp.nextval into :new.empno from dual;
--oracle 11g
:new.empno:=s_emp.nextval;
end;
-- The new data
insert into new_emp(ename,sal) values(' Zhang San ',2000)
select * from new_emp;
-- Row level triggers and statement level triggers
create or replace trigger t_emp
after
insert or update or delete
on new_emp
for each row
begin
dbms_output.put_line('ok');
end;
create or replace trigger t_emp2
after
insert or update or delete
on new_emp
begin
dbms_output.put_line('okok');
end;
select * from new_emp;
update new_emp set ename = ' ha-ha ' where ename = ' rees ';
边栏推荐
- Dish recommendation system based on graph database
- Masa Auth - SSO and Identity Design
- P1048 [noip2005 popularization group] Drug collection
- Sparksql of spark
- MySQL learning summary 12: system variables, user variables, definition conditions and handlers
- MySQL transaction isolation level experiment
- [200 opencv routines by youcans] 201 Color space conversion of images
- Simulink代码生成: 简单状态机及其代码
- Summary of rust language practice
- PostgreSQL common SQL
猜你喜欢

Panel data set of rural cities and towns: per capita consumption and expenditure of prefecture level cities 2012-2019 & rural data of provinces 2013-2019

Environmental pollution, enterprises, highways, fixed assets, foreign investment in all prefecture level cities in China - latest panel data

2000-2019 enterprise registration data of provinces, cities and counties in China (including longitude and latitude, number of registrations and other multi indicator information)

Figure data * reconstruction subgraph

Azure SQL db/dw series (10) -- re understanding the query store (3) -- configuring the query store

(九)详解广播机制

Sparksql of spark
![[azure data platform] ETL tool (5) -- use azure data factory data stream to convert data](/img/5c/79319a73881b645edaca77990f68a8.jpg)
[azure data platform] ETL tool (5) -- use azure data factory data stream to convert data

Spark Foundation
![[200 opencv routines by youcans] 201 Color space conversion of images](/img/99/36ba75cda08fd816dce83eaeea9e8d.png)
[200 opencv routines by youcans] 201 Color space conversion of images
随机推荐
English grammar_ Mode adverb position
[azure data platform] ETL tool (9) -- ADF performance optimization case sharing (1)
Spark optimization - data skew solution
Array in PHP array function_ Slice and array_ flip
Summary of rust language practice
测试写入mysql数据300W条,每次1.6-2W之间就断掉然后出现以下问题:
Domestic zynq standalone pl-ps interrupt commissioning
【面试复习】自用不定时更新
Transaction processing in PDO
C语言程序设计——从键盘任意输入一个字符串(可以包含:字母、数字、标点符号,以及空格字符),计算其实际字符个数并打印输出,即不使用字符串处理函数strlen()编程,但能实现strlen()的功能。
Nuggets new oil: financial knowledge map data modeling and actual sharing
Coal industry database - coal price, consumption, power generation & Provincial Civil and industrial power consumption data
Brief introduction: distributed cap theory and base theory
Serialization & deserialization
MapReduce internal execution principle
Spark Optimization -- differences and policy selection of RDD cache (cache, persist, checkpoint)
Yolov5 face+tensorrt: deployment based on win10+tensorrt8.2+vs2019
Figure data * reconstruction subgraph
Peking University HP financial index - matching enterprise green innovation index 2011-2020: enterprise name, year, industry classification and other multi indicator data
(九)详解广播机制