当前位置:网站首页>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 .
边栏推荐
- Guoguo took you to write a linked list, and the primary school students said it was good after reading it
- MySQL error resolution - error 1261 (01000): row 1 doesn't contain data for all columns
- Blue Bridge Cup Quick sort (code completion)
- jdbc连接es查询的时候,有遇到下面这种情况的大神嘛?
- Handwritten easy version flexible JS and source code analysis
- Preliminary study on temporal database incluxdb 2.2
- The idea of implementing charts chart view in all swiftui versions (1.0-4.0) was born
- 在所有SwiftUI版本(1.0-4.0)中原生实现Charts图表视图之思路
- Zephyr 學習筆記2,Scheduling
- Oracle-存储过程与函数
猜你喜欢
Book list | as the technical support Party of the Winter Olympics, Alibaba cloud's technology is written in these books!
Handwritten easy version flexible JS and source code analysis
JVM -- class loading process and runtime data area
Node foundation ~ node operation
Splicing plain text into JSON strings - easy language method
Used on windows Bat file startup project
University stage summary
Summary of MySQL common judgment functions!! Have you used it
The frost peel off the purple dragon scale, and the xiariba people will talk about database SQL optimization and the principle of indexing (primary / secondary / clustered / non clustered)
Introduction to neural network (Part 2)
随机推荐
tornado之目录
Master-slave replication principle of MySQL database
[Mori city] random talk on GIS data (I)
rapidjson读写json文件
Rhcsa the next day
提升复杂场景三维重建精度 | 基于PaddleSeg分割无人机遥感影像
BUUCTF(3)
神经网络入门(下)
Rapidjson reading and writing JSON files
Relations courantes de la fiche de données d'exploitation pour les activités
Electronic Association C language level 1 34, piecewise function
【Kubernetes系列】Kubernetes 上安装 KubeSphere
jdbc连接es查询的时候,有遇到下面这种情况的大神嘛?
[network security] what is emergency response? What indicators should you pay attention to in emergency response?
win10微软拼音输入法输入文字时候下方不出现中文提示
Computer connects raspberry pie remotely through putty
【森城市】GIS数据漫谈(一)
MySQL storage engine
L1-021 important words three times (5 points)
MySQL中的文本处理函数整理,收藏速查