当前位置:网站首页>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
边栏推荐
- Global and Chinese market of veterinary thermometers 2022-2028: Research Report on technology, participants, trends, market size and share
- Win: enable and disable USB drives using group policy
- Database postragesq BSD authentication
- Global and Chinese market of nutrient analyzer 2022-2028: Research Report on technology, participants, trends, market size and share
- Package What is the function of JSON file? What do the inside ^ angle brackets and ~ tilde mean?
- ROS command line tool
- Exploration and practice of integration of streaming and wholesale in jd.com
- [OpenGL learning notes 8] texture
- Unified blog writing environment
- Classification of performance tests (learning summary)
猜你喜欢
A simple SSO unified login design
Codeforces Global Round 19 ABC
Application and Optimization Practice of redis in vivo push platform
"2022" is a must know web security interview question for job hopping
Take you ten days to easily complete the go micro service series (IX. link tracking)
Main window in QT application
Redis master-slave replication cluster and recovery ideas for abnormal data loss # yyds dry goods inventory #
Remote control service
DOM basic syntax
Wechat applet; Gibberish generator
随机推荐
Win: enable and disable USB drives using group policy
Application and development trend of image recognition technology
Win:使用 Shadow Mode 查看远程用户的桌面会话
ROS command line tool
A simple SSO unified login design
Using openpyxl module to write the binary list into excel file
Basic operations of database and table ----- create index
85.4% mIOU! NVIDIA: using multi-scale attention for semantic segmentation, the code is open source!
线上故障突突突?如何紧急诊断、排查与恢复
Wechat applet: wechat applet source code download new community system optimized version support agent member system function super high income
【LeetCode】88. Merge two ordered arrays
[development of large e-commerce projects] performance pressure test - Optimization - impact of middleware on performance -40
Wechat applet: independent background with distribution function, Yuelao office blind box for making friends
Yyds dry goods inventory kubernetes management business configuration methods? (08)
Remote control service
MySQL backup and recovery + experiment
Es uses collapsebuilder to de duplicate and return only a certain field
Introduction to the gtid mode of MySQL master-slave replication
220213c language learning diary
微信小程序:微群人脉微信小程序源码下载全新社群系统优化版支持代理会员系统功能超高收益