当前位置:网站首页>Oracle stored procedures and functions
Oracle stored procedures and functions
2022-07-04 07:36:00 【Mr. Li, a genius】
Everything is inferior 、 Only reading is high
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 、 stored procedure
- 1、 Creation of stored procedures
- 2、 Calling and deleting stored procedures
- 3、 Use of stored procedures
- 1、 Create a stored procedure , towards student Insert a record in the table
- 2、 Create a stored procedure , Receive values from the outside , Judge whether the value is greater than zero in the stored procedure and display .
- 3、 Enter a number , Inquire about student Is there this number in the table , If yes, the name of the corresponding student will be displayed , If not, it will prompt that there is no corresponding student .
- 4、 Create a stored procedure , To the data table student Insert a record in .
- 5、 Enter a number , Inquire about student Is there this number in the table , If yes, return the name of the corresponding student , If not, it will prompt that there is no corresponding student .
- 4、 Query of stored procedure
- Two 、 function
- 3、 ... and 、 summary
One 、 stored procedure
A stored procedure is a named PL/SQL Data blocks , Stored in Oracle In the database , Can be called by user . Stored procedures can contain parameters , There can be no parameters , It usually has no return value . Stored procedures are pre compiled code , There is no need to compile again when calling again , Therefore, the operation efficiency of the program is very high .
1、 Creation of stored procedures
The grammar is as follows
create [or replace] The process of
[< Parameters 1> inioutin out < Parameter type >[ The default value is |:= Initial value ]]
[,< Parameters 2> inioutin out < Parameter type >[ The default value is |:= Initial value ],...]
isias
[ Local variable declaration ]
begin
Program statement sequence
[exception]
Exception handling statement sequence
end The process of
The parameters are described as follows :
1、or replace Optional parameters , Indicates that if the process to be created already exists in the database , Delete the original process first , Re establish the process , Or cover the original process .
2、 If there are parameters in the process , You need to use “inioutin out” keyword . If it's an input parameter , Then the parameter is followed by “in” keyword , It means to accept the value passed by the external process ; If it's an output parameter , Then the parameter is followed by “out” keyword , Indicates that this parameter will be copied in the process , And pass it to the process outside ; If it is “in out” Keyword indicates that the parameter has the characteristics of input parameter , It also has the characteristics of output parameters . The default is in Parameters , That is, if you don't write it, it defaults to in Parameters .
3、 Parameter type cannot specify length , Just give the type .
4、 Variables defined in the local variable declaration are only valid in this procedure .
5、 Local variable declaration , The definition and use of program statement sequence and exception handling statement sequence are the same as in the previous chapter PL/SQL block .
2、 Calling and deleting stored procedures
After a stored procedure is created , Exist in the form of compilation oracle In the database , Can be in sql plus Medium or pl/sql Call in block .
1、 stay sql plus Calling stored procedure in
The grammar is as follows :
execute The process of [ Parameter sequence ]
among execute It can be abbreviated as exec.
2、 stay pl/sql Call stored procedure in block
Write the process name directly to other pl/sql Block can be called , There is no need to use execute command .
3、 Deletion of stored procedure
Deleting a stored procedure is similar to deleting a table , The basic syntax is as follows .
drop procdure The process of
3、 Use of stored procedures
1、 Stored procedure without parameters
1、 Create a stored procedure , towards student Insert a record in the table
create or replace procedure pro_stu is
begin
insert into student<id,name,class> values<10,' Zhang San ',' the fifth class '>;
commit;
dbms_output.put_line<' Insert a new record !!!'>;
end pro_stu;
The above stored procedure has been successfully created , But it didn't execute , The execution statement is as follows .
exec pro_stu;
It's on it exec Command execution , We can also do that PL/SQL Directly call in the block , The grammar is as follows .
begin
pro_stu;
end;
2、 belt in Parameter stored procedure
Use in Parameters can input data to program units in stored procedures , Provide parameter values when calling , Read by stored procedure . This mode is the default parameter mode . Here is an example .
2、 Create a stored procedure , Receive values from the outside , Judge whether the value is greater than zero in the stored procedure and display .
create or replace procedure pro_decide<
var_num in number
> is
begin
if var_num>=0 then
dbms_output.put_line<' The parameter passed in is greater than or equal to 0'>;
else
dbms_output.put_line<' The parameter passed in is less than 0'>;
end if;
end pro_decide;
Execute stored procedures
exec pro_decide<3>;
Results show :
The parameter passed in is greater than or equal to 0
3、 Enter a number , Inquire about student Is there this number in the table , If yes, the name of the corresponding student will be displayed , If not, it will prompt that there is no corresponding student .
create or replace procedure pro_show<
var_stuid in student.id%type -- Definition in Parameters
> is
var_name student.name%type; -- Define stored procedure internal variables
no_result exception;
begin
select name into var_name from student where id = var_stuid; -- Value
if sql%found then
dbms_output.put_line<' The student name inquired is :' || var_name>; -- Show
end if;
when no_data_found then
dbms_output.put_line<' There is no student corresponding to this number '>; -- Error handling
end pro_show;
Execute stored procedures .
exec pro_show<10>
4、 Create a stored procedure , To the data table student Insert a record in .
create or replace procedure pro_add<
var_id in number,
var_name in varchar2,
var_class in varchar2> is
begin
insert into student values<var_id,var_name,var_class>; -- insert record
commit;
dbms_output.put_line<' Insert a new record !!!'>;
end pro_add;
Execute stored procedures
exec pro_add<10,' Zhang San ',' the fifth class '>;
5、 Enter a number , Inquire about student Is there this number in the table , If yes, return the name of the corresponding student , If not, it will prompt that there is no corresponding student .
We use in Is to display the student's name , Now we want to return the student's name and use out, The grammar is as follows
create or replace procedure pro_show1<
var_id in student.id%type, -- Definition in Parameters
var_name out student.name%type -- Definition out Parameters
> is
no_result exception;
begin
select name init var_name from student where id = var_id; -- Value
exception
when no_data_found then
dbms_output.put_line<' There is no student corresponding to this number '>; -- Error handling
end pro_show1;
Call contains out The stored procedure of parameters needs to declare a variable of corresponding type in advance , Then it is used to receive .
variable var_name varchar2<10>;
exec pro_show1<10,:var_name>;
At call time , Use “:” Followed by the variable name .
4、 Query of stored procedure
The query of stored procedure needs to use data dictionary user_source, The grammar is as follows
select distinct name from user_source where type=upper('procedure');
The above statement queries the names of all stored procedures under the current user .
Besides , We can also query the contents of stored procedures , The query statement is shown below .
select text from user_source where name = upper('pro_aa');
Two 、 function
The above stored procedure has input parameters and output parameters , But there is no return value , Functions are very similar to stored procedures , It can also be stored in oracle In the database PL/SQL Code block , But there is a return value , You can define a frequently used function as a function , Just like the function of the system ( For example, case conversion , Find the absolute value and other functions ) The use of .
1、 Function creation
The basic syntax format of function creation is as follows .
create or replace function Function name
[< Parameters 1> inioutin out < Parameter type >[ The default value is |:= Initial value ]]
return Return data type
isias
[ Local variable declaration ]
begin
Program statement sequence
[exception]
Exception handling statement sequence
end The process of
The parameters are described as follows .
1、or replace Optional parameters , Indicates that if the function to be created already exists in the database , Delete the original function first , Then rebuild the function , Or overwrite the original function .
2、 If there are parameters in the process , You need to use “inioutin out” keyword . If it's an input parameter , Then the parameter is followed by “in” keyword , It means to accept the value passed by the external process ; If it's an output parameter , Then the parameter is followed by “out” keyword , Indicates that this parameter will be copied in the process , And pass it to the process outside ; If it is “in out” Keyword indicates that the parameter has the characteristics of input parameter , It also has the characteristics of output parameters . The default is in Parameters , That is, if you don't write it, it defaults to in Parameters .
3、 Parameter type cannot specify length , Just give the type .
4、 The return value type of the function is required .
5、 The variables defined in the local variable declaration are only valid in this function .
6、 Local variable declaration 、 Definition and use of program statement sequence and exception handling statement sequence PL/SQL block .
In the main program of the function , You have to use return Statement returns the final function value , And the data type of the return value should be the same as the type specified when declaring .
## 2、 The creation and use of implicit cursors
> Different from the display cursor , Implicit cursors are automatically created by the system , Used for processing DML sentence ( for example insert、update、delete Such as instruction ) Or select Query the single row data returned , In this case, the implicit cursor is a pointer to the buffer . There is no need to declare when using 、 Open and close , So you don't need open、fetch、close Such operation instructions . Implicit cursors are also described above 4 Species attribute , When using, you need to add the default name of the implicit cursor in front of the attribute SQL, Therefore, implicit cursors are also called SQL The cursor .
### 1、 take student The age of Zhang San's students in the table increases 10 year , Then use an implicit cursor %rowcount Number of employees involved in attribute output
```go
begin
update student set age=age+10 -- Increase in age 10
where name = ' Zhang San ';
if sql%notfound then -- Whether there are qualified records
dbms_output.put_line<' No eligible students '>;
else
dbms_output.put_line<' The number of eligible students is :' || sql%rowcount>;
end if;
end;
2、 Function call and deletion
The calling method of function is basically the same as that of system built-in function . Can be directly in SQL plus Use in , It can also be used in stored procedures .
Deleting functions is similar to deleting stored procedures , The grammar is as follows :
drop function Function name
3、 Use of functions
1、 Create a function , If it is an even number, calculate its square , If it is an odd number, calculate its square root
create or replace function fun_cal
<var_num number> -- Declare function parameters
return number -- Declare the function return type
is
i int:=2;
begin
if mod<var_num,2>=0 then -- Judge parity
return power<var_num,i>; -- Return square
flse
return round<sqrt<var_num>,2>; -- Return square root
end if;
end fun_cal;
4、 Function query
In actual use, it is often necessary to query the existing functions in the database or the contents of a certain function , The method used is similar to that of stored procedures , You also need to use a data dictionary user_source, The query statements used are as follows .
select distinct name from user_source where type=upper('function');
The above statement queries the names of all user-defined functions under the current user .
Besides , We can also query the content of the function , The query statement is shown below .
select text from user_source where name=upper('fun_cal') and type=upper('function')
3、 ... 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 .
边栏推荐
- Mysql database - function constraint multi table query transaction
- flask-sqlalchemy 循环引用
- tornado之目录
- 【森城市】GIS数据漫谈(一)
- Boast about Devops
- Cell reports: Wei Fuwen group of the Institute of zoology, Chinese Academy of Sciences analyzes the function of seasonal changes in the intestinal flora of giant pandas
- Status of the thread
- NLP literature reading summary
- Comparison between applet framework and platform compilation
- jdbc连接es查询的时候,有遇到下面这种情况的大神嘛?
猜你喜欢
Vulhub vulnerability recurrence 76_ XXL-JOB
L2-013 red alarm (C language) and relevant knowledge of parallel search
The crackdown on Huawei prompted made in China to join forces to fight back, and another enterprise announced to invest 100 billion in R & D
Data double write consistency between redis and MySQL
在所有SwiftUI版本(1.0-4.0)中原生实现Charts图表视图之思路
Cell reports: Wei Fuwen group of the Institute of zoology, Chinese Academy of Sciences analyzes the function of seasonal changes in the intestinal flora of giant pandas
Computer connects raspberry pie remotely through putty
大厂技术专家:架构设计中常用的思维模型
Zhanrui tankbang | jointly build, cooperate and win-win zhanrui core ecology
Tri des fonctions de traitement de texte dans MySQL, recherche rapide préférée
随机推荐
Routing decorator of tornado project
System architecture design of circle of friends
线性代数1.1
Used on windows Bat file startup project
电子协会 C语言 1级 34 、分段函数
Text processing function sorting in mysql, quick search of collection
神经网络入门(下)
Adaptive spatiotemporal fusion of multi-target networks for compressed video perception enhancement
JVM中堆概念
Types of references in BibTex
BasicVSR++: Improving Video Super-Resolutionwith Enhanced Propagation and Alignment
Xcode 14之大变化详细介绍
大厂技术专家:架构设计中常用的思维模型
L1-022 odd even split (10 points)
Relations courantes de la fiche de données d'exploitation pour les activités
Life planning (flag)
Zabbix agent主动模式的实现
NLP literature reading summary
Literature collation and thesis reading methods
深入浅出:了解时序数据库 InfluxDB