当前位置:网站首页>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
边栏推荐
- [development of large e-commerce projects] performance pressure test - Performance Monitoring - heap memory and garbage collection -39
- MATLB|多微电网及分布式能源交易
- Wechat applet: the latest WordPress black gold wallpaper wechat applet two open repair version source code download support traffic main revenue
- Global and Chinese markets of radiation linear accelerators 2022-2028: Research Report on technology, participants, trends, market size and share
- 力扣剑指offer——二叉树篇
- Valentine's Day flirting with girls to force a small way, one can learn
- Five ways to query MySQL field comments!
- Database postragesq peer authentication
- Flutter 2.10 update details
- MySQL backup and recovery + experiment
猜你喜欢
Complex, complicated and numerous: illustration of seven types of code coupling
微信小程序:全网独家小程序版本独立微信社群人脉
[flutter topic] 64 illustration basic textfield text input box (I) # yyds dry goods inventory #
Comment mettre en place une équipe technique pour détruire l'entreprise?
After reading the average code written by Microsoft God, I realized that I was still too young
PHP wechat official account development
MySQL backup and recovery + experiment
Game 280 of leetcode week
Interesting practice of robot programming 14 robot 3D simulation (gazebo+turtlebot3)
Main window in QT application
随机推荐
Delaying wages to force people to leave, and the layoffs of small Internet companies are a little too much!
When the industrial Internet era is truly developed and improved, it will witness the birth of giants in every scene
WCF: expose unset read-only DataMember property- WCF: Exposing readonly DataMember properties without set?
pytorch fine-tuning (funtune) : 镂空设计or 偷梁换柱
当产业互联网时代真正发展完善之后,将会在每一个场景见证巨头的诞生
如何搭建一支搞垮公司的技术团队?
Summary of regularization methods
220213c language learning diary
Phpstrom setting function annotation description
Great God developed the new H5 version of arXiv, saying goodbye to formula typography errors in one step, and mobile phones can also easily read literature
Redis(1)之Redis简介
Remote control service
Discrete mathematics: Main Normal Form (main disjunctive normal form, main conjunctive normal form)
Can financial products be redeemed in advance?
【大型电商项目开发】性能压测-优化-中间件对性能的影响-40
Expansion operator: the family is so separated
Database postragesql client connection default
Application and Optimization Practice of redis in vivo push platform
微信小程序:独立后台带分销功能月老办事处交友盲盒
Win:使用 Shadow Mode 查看远程用户的桌面会话