当前位置:网站首页>Oracle PL / SQL programming
Oracle PL / SQL programming
2022-07-02 22:38:00 【Mr. Li, a genius】
If a worker wants to do a good job, he must sharpen his tools first
Articles are constantly updated , You can search by wechat 【 Xiaoqi JAVA interview 】 First time reading , reply 【 Information 】 Access to benefits , reply 【 project 】 Get the source code of the project , reply 【 The resume template 】 Get resume template , reply 【 Learning Roadmap 】 Get a learning roadmap .
List of articles
One 、 summary
PL/SQL Is in sql On the basis of , It's to deal with sql Some complex business logic processing that cannot be carried out .
1、 Program structure
A complete PL/SQL Statement blocks generally have 3 Component composition .
1: Declaration part (declare)
2: Executive part (begin)
3: Exception handling part (exception)
declare
Declaration part
begin
Executive part
exception
Exception handling part
end
Two 、 Constant
1、 Basic data type
1: value type
number,number(x,y),x Is the significant bit ,y It's a decimal place , for example number(5,2) Indicates that the definition of a significant bit is 5 position , The decimal places are 2 Of .
2: Character type
varchar2,char
varchar2 Used to store variable length strings ,char Type is used to store strings of a specified length .
3: The date type
date,timestamp
data Type stores date and time information ,timestamp Store in data similar , But it also includes the decimal part of the second
4: Boolean type
boolean
5:lob type
blob,clob,nclob,bfile
clob,nclob Store text data ,blob Store binary data ,bfile Store pointers to operating system files .
2、 Special data types
In addition to the basic data types above ,PL/SQL It also provides 3 A special data type , this 3 All data types are based on basic data types .
The syntax is as follows
type myrecord is record(
field1 datatype [not null][:=default value]
)
Define a record type myrecord, Used to store student Students' names and class names in the table
declare
type myrecord is record
my_name varchar2<20>,
my_class varchar2<20>;
Myrecord myrecord;
begin
select name,class into myrecord from student where id = 1;
dbms_output.put_line<' The student name inquired is :' || Myrecord.my_name ||', His class is :‘|| Myrecord.my_class >;
end;
3、%type type
stay oracle We often use the data types of fields in , When we define a data type to be consistent with the existing field types in the table, we can use %type type , For example, we declare a relation with student In the table name The field types are consistent var_name
var_name student.name%type
4、%rowtype type
You can tell by the name rowtype Represents all data types of a row in the data table , So you can record a row of data after using it . For example, declare a for storing student Variables recorded in each row of the table var_row
var_row student %rowtype
Declare one for storing student In the table id=1 One line of records var_row, And display basic information
declare
var_row student%rowtype;
begin
select * into var_row from student where id =1;
dbms_output.put_like<' The student name inquired is :' || var_row.name>
end;
5、 Record form type
The types we mentioned above can only store one data , Or a row of data , Cannot store multiple rows of data , Now we need to store multiple rows of data . The grammar is as follows
type Record table type name is table of type index by binary_integer
Define a record table type to store student Table data , And display
declare
type mytabletype is table of student%rowtype index by binary_integer;
Mytable mytabletype;
begin
select * into mytable<1> from student where id = 1;
select * into mytable<2> from student where id = 2;
dbms_output.put_line<' The student's name is :'|| mytable<1>.name>;
dbms_output.put_line<' The student's name is :'|| mytable<2>.name>;
end;
3、 ... and 、 Variable
1、 Definition of variables
We must first define variables in the declaration section , Not familiar with other programming languages ,PL/SQL Language requires variable names to be in front , The data type is later , The syntax for defining variables is as follows .
Variable name data type [ The default value is |: = Initial value ]
For example, the following code
var_name varchar2(20):=' Zhang San '
2、 The assignment of a variable
1: Direct assignment
name:=' Zhang San ';
age:=age+10;
2: Interactive assignment
name:=&temp;
Running this code will prompt for temp Value , Then assign the input value to name Variable
3: Use select In the query statement into Clause
select name into name_temp from student where id = 1;
3、 Scope of variable
Scope of variable , In a normal PL/SQL Fast mid , The scope of variables starts from the declaration , Until the end of the block . If there is block nesting , Then the externally declared is a global variable , It can be used externally or internally .
Four 、 Definition of constant
1、 Constant
The value of the constant remains unchanged during the running of the program , Constants are declared in a way similar to variables , But include keywords constant, When defining constants, initial values should be given , As shown below .
pi constant number:=3.1415;
5、 ... and 、 Conditional statements
if
case
1、if sentence
There are three forms :if…then sentence 、if…then…else Statement and if…then…elsif sentence .
1、if…then sentence
The basic syntax is as follows
if Conditional expression then
Statement sequence ;
end if;
When the result of the conditional expression is true when , The program runs then The following statement sequence , If false when , Then skip then Run the following end if Subsequent statements .
2、if…then…else sentence
The basic syntax is as follows
if Conditional expression then
Statement sequence 1;
else
Statement sequence 2;
end if;
When the result of the conditional expression is true when , Program running statement sequence 1, If false when , Run the statement sequence 2.
3、if…then…elseif sentence
The basic syntax is as follows
if Conditional expression 1 then
Statement sequence 1;
elseif Conditional expression 2
Statement sequence 2;
...
else
Conditional expression n
end if;
When the result of the conditional expression is true when , Program running statement sequence 1, If false when , Run the statement sequence 2.
2、case sentence
The grammar is as follows
case Selector expressions
when Conditions 1 then Statement sequence 1;
when Conditions 2 then Statement sequence 2;
...
when Conditions n then Statement sequence n;
else Statement sequence n+1;
end case;
6、 ... and 、 Loop statement
loop
while
for
1、loop loop
This kind of circulation includes the circulation conditions in the circulation body ,loop The loop will first execute the loop body , Then judge whether the set conditions are met to determine whether the cycle continues . The syntax is as follows
loop
Statement sequence ;
exit when Conditional expression
end loop
First execute the statement sequence , Then judge the next operation according to the value of the conditional expression , If the value of the conditional expression is true, Then exit the loop , If the value of the conditional expression is false, Then continue to execute the loop body .
2、while loop
while Loop is to judge the condition first , If the condition is true, execute the loop body , If not , Just exit the loop , The syntax is as follows .
while Conditional expression loop
Statement sequence ;
end loop;
When it's running , First, judge the conditional expression , If it turns out to be true, Then run the statement sequence in the loop body , If false, Then exit the loop .
3、for loop
The number of cycles in the first two cycles depends on whether the condition is true ,for The cycle can define the number of cycles by itself . The syntax is as follows
for Loop variable in [reverse] Start number ... End value loop
Statement sequence ;
end loop;
When the loop variable is greater than the starting value , When it is less than the end value , Execute a sequence of statements , Otherwise exit the loop , By default, loop variables are incremented in a loop , If used reverse Parameters , Then the cycle decreases .
7、 ... and 、 exception handling
A complete PL/SQL Statement blocks generally have 3 Component composition , Among them the first 3 The second part is the exception handling part ,oracle Provides exceptions (exception) And exception handling (exception handler) To achieve error handling . An error corresponds to an exception , When something goes wrong , The exception handler will catch the corresponding exception , The exception handler handles runtime errors .
1、 The kind of anomaly
oracle Runtime errors can be divided into oracle Errors and user defined errors , Corresponding to this , According to the mechanism and principle of exception generation , Can be Oracle The system exceptions of are divided into 3 Kind of .
1: Predefined exceptions : Corresponding to oracle error , yes Oracle Provided by the system itself , Users can go to PL/SQL The exception handling section represents them by name . Handling of these exceptions , Users do not need to define , By oracle Automatic triggering .
2: Non predefined exception : Other standards oracle error , How to deal with this abnormal situation , The user is required to define , Then from oracle Automatically trigger it .
3: User defined exception : Program execution , There is something abnormal that the programmer thinks . The handling of this exception requires the user to define , Then the displayed will trigger it in the program .
2、 Exception handling
1、 Exception definition
Abnormal variable excption
If it is a non predefined exception , You also need to associate this exception variable with the error number , The grammar is as follows
prama excption_int( Abnormal variable ,-#####)
among ,“#####” by oracle Error number of
2、 Exception correlation
In the execution part, when an error occurs, the exception corresponding to the error is associated , Because the system can automatically identify oracle internal error , Therefore, when an error occurs, the system will automatically associate the corresponding predefined exception or non predefined exception , But user-defined errors , The system cannot automatically recognize , User programming is required for Correlation , The associated syntax is as follows .
raise user_define_recption
3、 Exception catching and handling
When an error occurs , In the exception handling part, the exception is caught and handled by the exception handler . The grammar is as follows .
exception
when abnormal 1 [OR abnormal ......]then Process sequence statements 1;
when abnormal 2 [OR abnormal ......]then Process sequence statements 2;
...
when abnormal n [OR abnormal ......]then Process sequence statements n;
end;
An exception can only be caught by an exception handler , And process it
A processor can catch multiple exceptions , At this point through OR Connect
3、 Exception handling instance
Inquire about student In the table name by “ Zhang San ” Student information , If there is no such student , The output “ No data record returned ”, If there are multiple records , The output “ Return data record exceeds one line ”.
declare
var_name student.name%type;
begin
select name into var_name from student where name = ' Zhang San ';
if sql%found then -- If it's a line , It shows the results
dbms_output.put_line<' The student's name :' || var_name>;
end if;
exception
when too_many_rows then -- Capture exception
dbms_output.put_line<' Return data record exceeds one line '>;
when no_data_found then
dbms_output.put_line<' No data record returned '>;
end;
8、 ... and 、 summary
The relevant contents here have not been sorted out yet , The article continues to be updated later , Recommended collection .
The commands involved in the article must be typed several times each like me , Only in the process of knocking can you find out whether you really master the command .
You can search by wechat 【 Xiaoqi JAVA interview 】 First time reading , reply 【 Information 】 Access to benefits , reply 【 project 】 Get the source code of the project , reply 【 The resume template 】 Get resume template , reply 【 Learning Roadmap 】 Get a learning roadmap .
边栏推荐
- Riding the wind of "cloud native" and stepping on the wave of "digitalization", new programmer 003 starts pre-sale
- From "bronze" to "King", there are three secrets of enterprise digitalization
- How to center the positioned text horizontally and vertically
- Market Research - current market situation and future development trend of aircraft front wheel steering system
- 《Just because》阅读感受
- Hanoi Tower problem
- Promise optimized callback hell
- Simpleitk use - 4 Strange question
- Reading experience of just because
- PHP wechat red packet grabbing algorithm
猜你喜欢
[shutter] shutter resource file use (import resource pictures | use image resources)
[shutter] shutter page life cycle (initialization period | createstate | initstate | update period | build | destroy period | dispose)
[staff] Sibelius 7.5.1 score software installation (software download | software installation)
Infrastructure is code: a change is coming
Promise optimized callback hell
Reading experience of just because
开发者分享 | HLS, 巧用AXI_master总线接口指令的定制并提升数据带宽-面积换速度...
《Just because》阅读感受
分享一下如何制作专业的手绘电子地图
Developers share | HLS and skillfully use Axi_ Customize the master bus interface instructions and improve the data bandwidth - area exchange speed
随机推荐
[shutter] shutter custom fonts (download TTF fonts | pubspec.yaml configure font resources | synchronize resources | globally apply fonts | locally apply fonts)
Leetcode theme [array] -169- most elements
UE4 UI adaptive screen
Share how to make professional hand drawn electronic maps
服务可见可观测性
An overview of the development of affective computing and understanding research
#include errors detected. Please update your includePath.
Basic concepts of image and deep understanding of yuv/rgb
Market Research - current market situation and future development trend of third-party data platform
The difference between include < > and include ""
: last child does not take effect
What is it that makes you tremble? Those without fans can learn
Landingsite eband B1 smoke test case
[shutter] shutter opens a third-party application (url|launcher plug-in search and installation | url| launcher plug-in official example | open browser | open a third-party application)
Market Research - current situation and future development trend of sickle cell therapy Market
New feature of go1.18: trylock, which has been tossed n times
[QT] Q multithreaded development - Analysis of multithreaded application examples (Mandelbrot)
数学建模——图与网络模型及方法(一)
Market Research - current market situation and future development trend of high tibial osteotomy plate
UE4 UI自适应屏幕