当前位置:网站首页>Preliminary study of Oracle pl/sql
Preliminary study of Oracle pl/sql
2022-07-24 17:27:00 【Hanshhh】
PL/SQL brief introduction
PL/SQL(Procedure Language/SQL) The programming language is Oracle Yes sql The procedural extension of language , Referring to SQL A procedure processing statement is added to the command language ( Such as branches 、 Cycle, etc ), send SQL Language has the ability of process processing . hold SQL The data manipulation ability of language is combined with the data processing ability of process language , bring PLSQL Process oriented but simpler than process language 、 Efficient 、 Flexible and practical .
PL/SQL Grammatical structure
PL/SQL Block has four keywords :
- DECLARE: Declaration part .
- BEGIN: The executable part .
- EXCEPTION: Exception handling part .
- END: With keywords END end .
DECLARE
-- Declare variables 、 The cursor .
I INTEGER;
BEGIN
-- Execute statement
--[ exception handling ]
EXCEPTION
when NO_DATA_FOUND then
raise_application_error(-20000, 'No Data Found!');
END;
Example : Print Hello World
BEGIN
-- Print hello world
DBMS_OUTPUT.PUT_LINE('hello world');
END;
among DBMS_OUTPUT by oracle Built in packages , amount to Java Medium System.out, and PUT_LINE() Is the method called , amount to println() Method .
Variable
explain :
1、 It is recommended to follow the general rules for variable naming , such as v_name Represents a variable ,c_name Represents a constant ;
2、 It is generally recommended that each line declare a variable , In this way, the readability of the program is better ;
3、 If a variable is declared , But not initialized , Then the value of this variable is NULL; A good programming habit is to initialize and assign values to all declared variables .
Common data variables
(char,varchar2, date, number, boolean, long)
Example : Declare some common variables
DECLARE
v_job VARCHAR2(9);
v_count BINARY_INTEGER := 0;
v_total_sal NUMBER(9,2) := 0;
v_orderdate DATE := SYSDATE + 7;
c_tax_rate CONSTANT NUMBER(3,2) := 8.25;
v_valid BOOLEAN NOT NULL := TRUE;
Special variable types
Referential variables
1、 Use the direct assignment statement to assign := such as :v_name := 'hans'
2、 utilize select...into... Statement assignment :( grammar select value into Variable )
select 'name'
into v_name
from student;
// take student Tabular name The value of is assigned to v_name
notes :PLSQL Use unique %TYPE Attribute to declare and XX Variable types with consistent types
for example : State the name of the employee 、 Employee salary has two fields , You can use the following syntax
DECLARE
v_name emp.ename%TYPE;
v_salary emp.esalary%TYPE;
BEGIN
SELECT ENAME,ESALARY
into v_name,v_salary
FROM EMP
WHERE ROWNUM=1;
END;
Record variables
Accept a whole row of records in the table , amount to Java One of the objects in
grammar : Variable name Table name %ROWTYPE,
v_emp emp%ROWTYPE;
SELECT *
into v_emp
FROM EMP
WHERE ROWNUM=1 ;
DBMS_OUTPUT.put_line(v_emp.ename||','||v_emp.esalary);
-- We can use the record variable name defined by us to directly point it out
-- || It means string connection
-- If there is a table , Yes 100 A field , So if your program wants to use this 100 Field words , If you use reference variables, declare them one by one , It's going to be a lot of trouble , Record variables can easily solve this problem .
-- Record type variables can only store one complete row of data , Only one line , Multiple lines will report errors
-- Example :type numbers is table of number index by binary_integer
-- added ”index by binary_integer ” after ,numbers The subscript of type is self growth , You can automatically find the corresponding value according to the subscript .
--numbers Type when inserting an element , No initialization required , You don't need to extend Add a space .
DECLARE
TYPE emp_table_type is table of
employees%ROWTYPE INDEX BY BINARY_INTEGER;
my_emp_table emp_table_type; -- rename
v_count NUMBER(3):= 104;
BEGIN
FOR i IN 100..v_count --i No need to define , from 100 Increase to v_count
--(IN Back plus REVERSE It can be expressed in reverse order )
LOOP
SELECT * INTO my_emp_table(i) FROM employees -- Automatically find the corresponding value according to the subscript
WHERE employee_id = i;
END LOOP;
FOR i IN my_emp_table.FIRST..my_emp_table.LAST
LOOP
DBMS_OUTPUT.PUT_LINE(my_emp_table(i).last_name);
END LOOP;
END;
Process control
1、 Conditional branch
begin
IF Conditions 1 THEN perform 1
ELSIF Conditions 2 THEN perform 2
ELSE perform 3
END IF;
end;
-- Pay attention to keywords :ELSIF
2、 loop
BEGIN
LOOP
EXIT WHEN Exit cycle conditions
END LOOP;
END;
-- exit when Is the condition for exiting the loop
Example :
【 Example 】 Print digit 1-10
DECLARE
-- Declare loop variables
V_NUM NUMBER := 1; -- Common variables , Use it directly := assignment
BEGIN
LOOP -- Circular keywords , Loop start
EXIT WHEN V_NUM > 10; -- Conditions for exiting the loop
DBMS_OUTPUT.PUT_LINE(V_NUM); -- Print variables
-- Self increasing of cyclic variables
V_NUM := V_NUM + 1;
END LOOP; -- The loop ends
END;
SQL sentence
INSERT、UPDATE、DELETE 、MERGE sentence : stay PLSQL To perform these SQL Statements are similar to executing these statements directly , It's just that you can SQL Use in statement PLSQL Declared variables ;
-- Example
DECLARE
v_sal_increase employees.salary%TYPE := 800;
BEGIN
UPDATE employees
SET salary = salary + v_sal_increase
WHERE job_id = 'ST_CLERK';
END;
notes :SQL Function in PLSQL The use of procedure statements :
majority SQL Functions can be in PLSQL Used in the procedure statement of , such as :
Single line numeric and string functions 、 Data type conversion function 、 Date function 、 Time function 、 Ask for the biggest 、 The minimum GREATEST, LEAST Functions, etc ;
But some functions are PLSQL Cannot be used in the procedure statement of , such as :
Decode function 、 Group function (AVG, MIN, MAX, COUNT, SUM, STDDEV, and VARIANCE) etc. ;
The cursor
Used to temporarily store multiple rows of data returned by a query ( Result set , Be similar to Java Of Jdbc Connection returned ResultSet aggregate ), By traversing the cursor , The data processing the result set can be accessed row by row .
How to use cursors : Statement —> open —> Read —> close grammar
Cursor declaration : CURSOR You name [( parameter list )] IS Query statement ;
The opening of the cursor : OPEN You name ;
The value of the cursor : FETCH You name INTO Variable list ;( The data of the cursor is placed in the variable list )
Cursor closing ;CLOSE You name ;
Properties of the cursor Properties of the cursor ———— return type ———— explain
%ROWCOUNT----------- integer ---------- get FETCH Statement returns the entire row of data
%FOUND------------ Boolean type --------------- Current FETCH Statement returns a row of data, which is true , Otherwise it is false ( Can get data and return a piece of data , It is true )
%NOTFOUND-------------- Boolean type ----------- And %FOUND Property returns the opposite value ( It is generally used to judge whether to exit the cycle )
%ISOPEN---------------- Boolean value ------------- The value is true when the cursor has been opened , Otherwise it is false
among %NOTFOUND Returns when the element cannot be found in the cursor TRUE, Usually used to determine whether to exit the loop .
【 Example 】: Use cursor query emp Names and salaries of all employees in the table , And print them out in turn .
DECLARE
-- declare cursor -- Cursor without parameters
CURSOR C_EMP IS -- Define the name of the cursor
SELECT ENAME, ESALARY FROM EMP; -- Query statement
-- Declare that variables accept data from cursors
V_ENAME EMP.ENAME%TYPE;
V_SALARY EMP.ESALARY%TYPE;
BEGIN
-- Open cursor
OPEN C_EMP;
-- Traversal cursor
LOOP
-- Get the data in the cursor
FETCH C_EMP
INTO V_ENAME, V_SALARY; -- Copy the obtained data to the variables we define
-- Exit cycle conditions
EXIT WHEN C_EMP%NOTFOUND; --exit when yes loop Loop out statement ,C_EMP Is the name of the cursor , --%NOTFOUND There is no data in the cursor. Return true,
--EXIT WHEN C_EMP%NOTFOUND The cursor has no data and returns true 了 , Conditions that promote exit from the cycle
DBMS_OUTPUT.PUT_LINE(' full name :' || V_ENAME || ' Salary :' || V_SALARY); -- Output cycle printing
END LOOP; -- The loop ends
-- Close cursor
CLOSE C_EMP;
END;
Cursors with parameters :
DECLARE
-- declare cursor
CURSOR C_EMP(V_EDEPNO emp.edepno%type) IS
SELECT ENAME, ESALARY FROM EMP WHERE EDEPNO=V_EDEPNO;
-- Declare that variables accept data from cursors
V_ENAME EMP.ENAME%TYPE;
V_SALARY EMP.ESALARY%TYPE;
BEGIN
-- Open cursor
OPEN C_EMP('a'); -- Parameters passed into the cursor a
-- Traversal cursor
LOOP
-- Get the data in the cursor
FETCH C_EMP
INTO V_ENAME, V_SALARY;
-- Exit cycle conditions
EXIT WHEN C_EMP%NOTFOUND;
DBMS_OUTPUT.PUT_LINE(' full name :' || V_ENAME || ' Salary :' || V_SALARY);
END LOOP;
-- Close cursor
CLOSE C_EMP;
END;
FOR UPDATE NOWAIT sentence : Sometimes we open a cursor to update or delete some records , In this case, we hope
When the cursor is opened, the relevant records are locked , You should use for update nowait sentence , If the lock fails, we will stop and stop , lest
Deadlock occurs when waiting for resources for a long time .
DECLARE
CURSOR emp_cursor IS
SELECT employee_id, last_name, department_name
FROM employees,departments
WHERE employees.department_id =
departments.department_id
AND employees.department_id = 80
FOR UPDATE OF salary NOWAIT; -- take salary Field lock
WHERE CURRENT OF cursor : Do in the circulatory system Update perhaps Delete There needs to be Where Point to the current record of the cursor
DECLARE
CURSOR sal_cursor IS
SELECT e.department_id, employee_id, last_name, salary
FROM employees e, departments d
WHERE d.department_id = e.department_id
and d.department_id = 60
FOR UPDATE OF salary NOWAIT;
BEGIN
FOR emp_record IN sal_cursor -- take sal_cursor Put your data in emp_record Result set
LOOP
IF emp_record.salary < 5000 THEN
UPDATE employees
SET salary = emp_record.salary * 1.10
WHERE CURRENT OF sal_cursor; --Where Point to the current cursor record
END IF;
END LOOP;
END;
RAISE_APPLICATION_ERROR() function : For user-defined business errors , If you think it's troublesome to define before using , that
It can also be used simply raise_application_error() To simplify processing . It can eliminate the need for pre-defined errors , And when you need to throw errors
Where you can use this function directly to throw exceptions , Can exceptions contain user-defined errors and error descriptions ;
EXCEPTION
WHEN NO_DATA_FOUND THEN
RAISE_APPLICATION_ERROR (-20201,'Manager is not a valid employee.');
END;
stored procedure
General sql Statements are compiled every time they are executed , Stored procedures are compiled only at creation , There is no need to recompile every time the stored procedure is executed in the future , So using stored procedures can speed up database execution .
When doing complex operations on a database ( For example, for multiple tables Update,Insert,Query,Delete when ), This complex operation stored procedure can be encapsulated and used in combination with the transaction processing provided by the database . These operations , If it is completed by program , It becomes one by one SQL sentence , You may need to connect to the database more than once . Instead of storing , You only need to connect to the database once .
Stored procedures can be reused , Can reduce the workload of database developers , High safety , It can be set that only a certain user has the right to use the specified stored procedure .
create or replace procedure The process of [( parameter list )] is
-- Not used declare Declare variables , But you can begin Declare variables directly above
begin
-- Executive part
end [ The process of ] ;
-- is Exchangeable as
for example :
CREATE OR REPLACE PROCEDURE raise_salary
(p_id IN employees.employee_id%TYPE)
IS
BEGIN
UPDATE employees
SET salary = salary * 1.10
WHERE employee_id = p_id;
END raise_salary;
Calling stored procedure : After compiling the stored procedure to be called , Reopen a test window, stay begin Directly enter the name of the stored procedure in .
Example : With input parameters IN And output parameters OUT Stored procedure
-- Enter employee name , take “HELLO Employee name ” Output as return value ,in Input parameters ,out Output parameters
create or replace procedure P_PRINT_HELLO (V_ENAME IN EMP.ENAME%TYPE,V_RETURN out VARCHAR2) is
-- Declare variables
begin
V_RETURN:='HELLO '||V_ENAME; -- := Assignment of common variables
end P_PRINT_HELLO;
Parameter transfer mode ( Pass... In order perhaps Use => Symbol transmission )
CREATE OR REPLACE PROCEDURE add_dept
(p_name IN departments.department_name%TYPE DEFAULT 'unknown',
p_loc IN departments.location_id%TYPE DEFAULT 1700)
IS
BEGIN
INSERT INTO departments(department_id,department_name, location_id)
VALUES (departments_seq.NEXTVAL, p_name, p_loc);
END add_dept;
BEGIN
add_dept; -- Use the default value
add_dept ('TRAINING', 2500); -- Pass... In order
add_dept ( p_loc => 2400, p_name =>'EDUCATION'); -- Use => Symbol transmission , No sequence requirements .
add_dept ( p_loc => 1200) ;
END;
-- Delete stored procedure
DROP PROCEDURE procedure_name
Storage function
-- Define function syntax
CREATE [OR REPLACE] FUNCTION function_name
[(parameter1 [mode1] datatype1,
parameter2 [mode2] datatype2,
. . .)]
RETURN datatype
IS|AS
PL/SQL Block;
-- Example
CREATE OR REPLACE FUNCTION get_sal
(p_id IN employees.employee_id%TYPE)
RETURN NUMBER -- Function return value ( Distinguish stored procedures )
IS
v_salary employees.salary%TYPE :=0;
BEGIN
SELECT salary
INTO v_salary
FROM employees
WHERE employee_id = p_id;
RETURN v_salary; -- Finally, you need to return parameters
END get_sal;
User defined functions must meet the following conditions :
- It has to be a function ( It cannot be a process -Procedure)
- Only use IN Parameters of the pattern ( Can not have OUT, IN OUT Parameters of the pattern )
- receive calls only SQL Parameters of data type , Can't receive PLSQL Parameters unique to ( Like records 、PLSQL Memory tables )
- The data type returned by the function must also be a valid data type , And can't be PLSQL Unique data types
- stay SQL Functions used in , Its function body cannot have DML sentence
- stay UPDATE/DELETE The function that is called in the statement , The function body cannot have query statements for the same table
- stay SQL Functions invoked in , Its function body cannot have a transaction end statement ( such as Commit,Rollback)
-- Delete storage function
DROP FUNCTION function_name
边栏推荐
- 电脑监控是真的吗?4个实验一探究竟
- Opencv has its own color operation
- The orders in the same city are delivered in the same city, and the order explosion is still handy!
- [GNN report] Tencent AI Lab Xu TingYang: graph generation model and its application in molecular generation
- 量化框架backtrader之一文读懂Indicator指标
- Portmap port forwarding
- Still shocked by the explosion in the movie? Then you must not miss this explosive plug-in of unity
- Are the top ten securities companies safe and risky to open accounts?
- Pat a - correct spelling
- Yolopose practice: one-stage human posture estimation with hands + code interpretation
猜你喜欢

portmap 端口转发

The orders in the same city are delivered in the same city, and the order explosion is still handy!

Opencv has its own color operation

NPM install reported -4058 error

The results of the second quarter online moving people selection of "China Internet · moving 2022" were announced

Live review | wonderful playback of Apache pulsar meetup (including PPT download)

Analog electricity - what is the resistance?

Atcoder beginer 202 e - count descendants (heuristic merge on heavy chain split tree for offline query)

Scroll bar adjust brightness and contrast

Exception handling - a small case that takes you to solve NullPointerException
随机推荐
Pat a - correct spelling
Using unity to do simulation, I don't allow this chart plug-in, you don't know
DBF menu driver: librarydatabaseproject
Natbypass port forwarding
MySQL addition, deletion, modification, retrieval and constraint (detailed teaching)
Stop littering configuration files everywhere! Try our 7-year-old solution, which is stable
2022 ranking list of database audit products - must see!
UFW port forwarding
Topic 6 - message queue for client communication
Can Lu Zhengyao hide from the live broadcast room dominated by Luo min?
什么是模糊理论,基础,流程
数论整除分块讲解 例题:2021陕西省赛C
图像像素的逻辑操作
2022 Asia International Internet of things exhibition
Baidu PaddlePaddle easydl x wesken: see how to install the "eye of AI" in bearing quality inspection
nc 端口转发
Heuristic merging (including examples of general formula and tree heuristic merging)
Is it safe for qiniu to open an account?
Xxx.pro learning in QT
Kernel development