当前位置:网站首页>Stored procedure and stored function in Oracle
Stored procedure and stored function in Oracle
2022-07-05 01:42:00 【Milk coffee 13】
One 、 stored procedure
1.1、 The introduction of stored procedure
stored procedure (Stored Procedure) In a large database system , A group of SQL Statements set , After compilation, it is directly stored in the database , The user calls the name of the specified stored procedure and passes the corresponding parameters ( If the stored procedure has parameters ) To execute it. . Stored procedure is an important object in database , Any well-designed database application has stored procedures .
1.2、 Advantages and disadvantages of stored procedures
| Serial number | stored procedure 【Stored Produce】 The advantages of |
| 1 | Stored procedure can make program execution more efficient 、 Better security , Because after the process is created and saved, it has been compiled and stored in the database , And write directly sql Statements need to be parsed by the analyzer before execution, so the process is more efficient , And write directly sql Statement may cause some security problems , Such as :sql Inject etc. |
| 2 | The establishment of stored procedures consumes little system resources ( This is because stored procedures are only executed when called ) |
| 3 | Stored procedures can be used to reduce network traffic ( This is because the code of the stored procedure is directly stored locally in the database , Call directly , Instead of writing a lot of sql Code for statement ) |
| 4 | Stored procedures enable you to enhance the reuse of execution plans |
| 5 | High maintainability ( This is because updating stored procedures is usually better than changing 、 Testing and redeploying assemblies takes less time and effort ) |
| 6 | The code is concise and consistent ( A stored procedure can be used in different locations of the application code ) |
| 7 | Enhance security ( ① By granting access to stored procedures to users ( Not based on tables ) Access rights of , They can provide access to specific data ; ② Improve code security , prevent SQL Inject ; ③SqlParameter Class specifies the data type of stored procedure parameters , As part of a deep defensive strategy , You can verify the value type provided by the user ) |
| Serial number | stored procedure 【Stored Produce】 Deficiency |
| 1 | Extensive use of stored procedures , It's going to put a lot of pressure on the server |
1.3、 Creation syntax of stored procedure
| Serial number | Parameter type description |
| 1 | IN Is the default mode of the parameter , This pattern is When the program is running, it already has a value , The value in the program body does not change |
| 2 | OUT Pattern Defined parameters can only be assigned inside the procedure body , Indicates that the parameter can pass a value to the callback with its procedure |
| 3 | IN OUT Express This parameter can pass a value to this procedure , You can also pass a certain value |
// Basic grammar
create [or replace] procedure Stored procedure name
( Parameter name in|out Parameter type , Parameter name in|out Parameter type ) is|as
- - Variable declaration part
begin
- - Business logic part
end;
// Detailed grammatical content
create [or replace] procedure Stored procedure name
(param1 in type,param2 out type) is|as
Variable 1 type ( Range of values );
Variable 2 type ( Range of values );
begin
select count(*) into Variable 1 from surface A where Name =param1;
if ( Judge the condition ) then
select Name into Variable 2 from surface A where Name =param1;
dbms_output.Put_line(' Print information ');
elsif ( Judge the condition ) then
dbms_output.Put_line(' Print information ');
else
raise Exception names (NO_DATA_FOUND);
end if;
exception
when others then
rollback;
end;1.4、 Syntax for executing stored procedures
Method 1 :
// Execute stored procedure syntax 1
CALL Stored procedure name ( Parameters 1, Parameters 2);
// Example of executing a stored procedure
CALL CACULATESALARY(1,5000);Method 2 :
// Execute stored procedure syntax 2
BEGIN
Stored procedure name ( Parameters 1, Parameters 2);
END;
// Example of executing a stored procedure
BEGIN
caculatesalary(1,5000);
END;1.5、 Examples of stored procedures
Example 1: To enter the employee number and the amount of salary increase, first view the original salary ; Then update the employee's salary , Then print it out and check ; Finally, if the update fails, you need to rollback .
The contents of the table are as follows :

The stored procedure is as follows :
CREATE OR REPLACE PROCEDURE CaculateSalary
(peopleNumber in NUMBER,needIncreaseSalaryNumber in NUMBER)
AS
TotalSalary NUMBER:=0;
BEGIN
-- Get the current salary
SELECT SALARY INTO TotalSalary from PEOPLE WHERE PEOPLE.ID=peopleNumber;
-- The salary before outputting a salary
dbms_output.put_line(' The salary before the salary rise is :'||TotalSalary);
-- Salary after salary increase
UPDATE PEOPLE SET SALARY=(TotalSalary+needIncreaseSalaryNumber) WHERE ID=peopleNumber;
-- The salary after outputting a salary
dbms_output.put_line(' After the salary increase, the salary is :'||(TotalSalary+needIncreaseSalaryNumber));
-- Commit transaction
commit;
-- If an exception occurs, rollback
EXCEPTION
WHEN OTHERS THEN
rollback;
dbms_output.put_line(' Execute rollback operation for abnormal salary increase ');
END; 
Example 2: You want to pass in parameters , Then pass the content through this parameter
CREATE OR REPLACE procedure testInuptOutput
(message in out varchar2)
-- When you want to bring in value , Want to take value out again , It can be used in out
as
begin
dbms_output.put_line(' The current input is :'||message); -- The output is the value carried in
message:=' I am the processed value '||998;
end; 
Two 、 Storage function
2.1、 Introduction to storage function
Storage function (Stored Function) It is saved in the database after creation , And encapsulated in oracle A section in the server has been completed plsql code snippet .
2.2、 Characteristics of storage functions
| Serial number | Characteristics of storage functions |
1 | Automatically load when the database starts |
| 2 | Function has no parameter input and output |
| 3 | Function must have a return value |
| 4 | When calling a function, you must use its return value |
| 5 | The storage function can be in sql Use in statement , It can also be in plsql Use in |
2.3、 Storage function creation syntax
| Serial number | Parameter type description |
| 1 | IN Is the default mode of the parameter , This pattern is When the program is running, it already has a value , The value in the program body does not change |
| 2 | OUT Pattern Defined parameters can only be assigned inside the procedure body , Indicates that the parameter can pass a value to the callback with its procedure |
| 3 | IN OUT Express This parameter can pass a value to this procedure , You can also pass a certain value |
// Basic syntax for storing functions
create [for replace] function The name of the storage function ( Parameter name in|out Parameter type , Parameter name in|out Parameter type )
return Parameter type
is | as
begin
end;
// The detailed syntax of the storage function
Create [or replace] function The name of the function ( Parameter name in|out Parameter type , Parameter name in|out Parameter type ,...)
Return Result variable data type
Is | as
Variable declaration part ;
Begin
Logical part ;
Return Outcome variable ;
[exception Exception handling part ]
End;
Be careful :end hinder ; Cannot cancel . The parameter list defaults to the input type in
2.4、 Syntax for executing storage functions
// Execute the storage function method 1( Put in expression )
SELECT The name of the function ( Parameters ) FROM dual;
// Execute the storage function method 1 Example
SELECT TIMEGROUP(TO_DATE('2022-02-12 17:30:36', 'yyyy-MM-dd hh24:mi:ss'))handleTime FROM dual;// Execute the storage function method 2
declare
Variable name type ;
begin
-- Assign storage function results to variables
Variable name := Store function name
-- Print variable results
dbms_output.put_line( Variable name );
end;
// Execute the storage method 2 Example
declare
result varchar(16);
begin
result:= TIMEGROUP(TO_DATE('2022-02-12 17:30:36', 'yyyy-MM-dd hh24:mi:ss'));
dbms_output.put_line(result);
end;
2.5、 Storage function example
Example : Group dates ( namely : The group with an interval of one hour starting from half an hour
①【 such as :2022-02-13 07:30:00 Until 2022-02-13 08:29:59】 Of is classified as 2022-02-13 08:30:00
②【 such as :2022-02-13 08:30:00 Until 2022-02-13 09:29:59】 Of is classified as 2022-02-13 09:30:00)
The storage function is as follows :
CREATE OR REPLACE FUNCTION TimeGroup(inputDate IN DATE) RETURN VARCHAR2
AS
result VARCHAR(16):='';
input_yyyy_MM_dd_hh24 VARCHAR(13):=to_char(inputDate,'yyyy-MM-dd hh24');
tmp_timegroup DATE:=TO_DATE(input_yyyy_MM_dd_hh24||'30:00','yyyy-MM-dd hh24:mi:ss');
BEGIN
IF inputDate>=tmp_timegroup
THEN result:=SUBSTR(TO_CHAR((tmp_timegroup+1/24),'yyyy-MM-dd hh24:mi:ss'),0,16);
ELSE result:=SUBSTR(TO_CHAR((tmp_timegroup),'yyyy-MM-dd hh24:mi:ss'),0,16);
END IF;
RETURN result;
END;


3、 ... and 、 The similarities and differences between stored procedures and stored functions
| Serial number | The similarities between stored procedures and stored functions |
| 1 | Create grammatical structures similar to , Can carry multiple incoming and outgoing parameters |
| 2 | It's all a compilation , Multiple runs |
| 3 | You can use 【in/ out /in out】 The parameters of the three modes |
| stored procedure | Storage function |
| Used to complete specific operations in the database ( Or task )【 The process is usually designed to find several operation results , Complete a series of data processing , Or various operations unrelated to calculation 】( such as : Insert 、 to update 、 Delete and other operations ) | For specific data operations 【 Just to get a value 】( such as : classified 、 grouping ) |
| Program header use 【Procedure】 Statement | Program header use 【Function】 Statement |
| No return type is required for program header declaration | The return type must be described when declaring the program header , And must be PL/SQL The block contains a valid return sentence |
| Can be used as an independent PL/SQL Statement to execute | Cannot execute independently , Must be called as part of the expression |
| Can pass out /in out Returns zero or more values | ① adopt return Statement returns a value , And the return value must be consistent with the declared content ; ② It can also be done through out Type parameters bring out variables |
| SQL sentence (DML or SELECT) Cannot call stored procedures in | SQL sentence (DML or SELECT) Storage functions can be called in |
Four 、 Other information
Why do I need to write stored procedures in the development process - Fat house bag - Blog Garden (cnblogs.com)
https://www.cnblogs.com/doudouxiaoye/p/5804467.html Stored procedure is enough - You know (zhihu.com)
https://zhuanlan.zhihu.com/p/137896709
Oracle Stored procedures and custom functions - cloud + Community - Tencent cloud (tencent.com)
https://cloud.tencent.com/developer/article/1861667
oracle stored procedure ( One ): Simple introduction - i Loner - Blog Garden (cnblogs.com)
https://www.cnblogs.com/dc-earl/articles/9260111.html Oracle The basic writing method of stored procedure - Repeated defeats and battles - Blog Garden (cnblogs.com)
https://www.cnblogs.com/joeyJss/p/11458653.html
边栏推荐
- 流批一体在京东的探索与实践
- Wechat applet: Xingxiu UI v1.5 WordPress system information resources blog download applet wechat QQ dual end source code support WordPress secondary classification loading animation optimization
- I use these six code comparison tools
- [CTF] AWDP summary (WEB)
- Async/await you can use it, but do you know how to deal with errors?
- Summary of regularization methods
- Basic operation of database and table ----- the concept of index
- MATLB | multi micro grid and distributed energy trading
- 如何搭建一支搞垮公司的技术团队?
- What is the current situation and Prospect of the software testing industry in 2022?
猜你喜欢

To sort out messy header files, I use include what you use

Mysql database | build master-slave instances of mysql-8.0 or above based on docker

Wechat applet; Gibberish generator

R语言用logistic逻辑回归和AFRIMA、ARIMA时间序列模型预测世界人口

Async/await you can use it, but do you know how to deal with errors?

Exploration and Practice of Stream Batch Integration in JD

Yyds dry inventory swagger positioning problem ⽅ formula

Wechat applet: wechat applet source code download new community system optimized version support agent member system function super high income

Roads and routes -- dfs+topsort+dijkstra+ mapping

Main window in QT application
随机推荐
Global and Chinese market of optical densitometers 2022-2028: Research Report on technology, participants, trends, market size and share
[development of large e-commerce projects] performance pressure test - Performance Monitoring - heap memory and garbage collection -39
What is the length of SHA512 hash string- What is the length of a hashed string with SHA512?
Mysql database | build master-slave instances of mysql-8.0 or above based on docker
pytorch fine-tuning (funtune) : 镂空设计or 偷梁换柱
如果消费互联网比喻成「湖泊」的话,产业互联网则是广阔的「海洋」
PHP 约瑟夫环问题
Interpretation of mask RCNN paper
Global and Chinese markets for industrial X-ray testing equipment 2022-2028: Research Report on technology, participants, trends, market size and share
Interesting practice of robot programming 14 robot 3D simulation (gazebo+turtlebot3)
Global and Chinese market of network connected IC card smart water meters 2022-2028: Research Report on technology, participants, trends, market size and share
Vulnstack3
[swagger]-swagger learning
PHP wechat official account development
Pytorch common code snippet collection
Change the background color of a pop-up dialog
Basic operations of database and table ----- create index
batchnorm.py这个文件单GPU运行报错解决
Codeforces Global Round 19 ABC
Educational Codeforces Round 122 (Rated for Div. 2) ABC