当前位置:网站首页>Use of Oracle PL-SQL
Use of Oracle PL-SQL
2022-06-13 03:37:00 【Mouth strong programmer】
Use PL-SQL
1. About PL-SQL( function 、 Features and grammatical structure )
2. data type (%type And %rowtype)
3.PL-SQL Control statement
4. exception handling
5. function
============================================
PL/SQL It's process language PL And structured query language SQL Combined programming language .
PL/SQL Is aimed at Oracle Database ;
It is a process language + The combination of structured query languages ;Process language PL: Such as variable declaration , Process control , Cycle, etc ;
query language SQL:SQL Language , Ruzeng 、 Delete 、 Change 、 Check etc ;
PL/SQL yes SQL The extended version of ,SQL What can be done ,PL/SQL Most of them can do .
PL/SQL The advantages of :
1. Support SQL: Data manipulation command , Transaction control command , slider control ,SQL Functions and SQL Operator ;
2. Support for object-oriented programming ;
3. Portability , Can run on any operating system ;
4. After compiling and executing , Good performance ;
5. And SQL Tight integration , Simplify data processing , Support SQL data type , Support NULL value , Support %type and %rowtype Attribute types (oracle The most interesting thing in );
6. SecurityPL/SQL It's divided into three parts :
1. Declaration part
2. The executable part
3. Abnormal schistosity
Grammatical structure :
[declare declaration] -- Declaration part
begin
executable statements -- The executable part
[exception handlers] -- Abnormal area
end;
Output :
select 'abc' from dual;
dbms_output.put_line('abc');-- Printout ( Must bring begin)
begin
dbms_output.put_line('abc');
endassignment :( := )
-- Variable declaration assignment , And print
declare i number(6);
begin
i:=77; //:= assignment ,select...into It's also an assignment
dbms_output.put_line(i);
end;-- stay emp The job number in the table is 7369 Name output for
declare sid number;
sname varchar2(22);
begin
sid:=7369;
select ename into sname from emp where empno=sid; --select...into Assignment method
dbms_output.put_line(sname);
end;At the prompt : stay begin with select sentence , Be sure to use select…into.
===========================================
data type :
1. Scalar type
2.LOB type
3. Attribute types :
%type: Provide the data type of a variable or database table column
%rowtype: Provide the record type of a row in the table ( Very distinctive )
3.1 %type-- seek 7369 Date of employment ( Without knowing what type the column is )
-- Apply for one with “ Date of entry ” Samedeclare sid number;
shiredate emp.hiredate%type; -- Declare a variable , Its type is the same as that of a column in the table
begin
sid:=7369;
select hiredate into shiredate from emp where empno=sid;
dbms_output.put_line(shiredate);
end;-- It's fine too sb shiredate%type;
-- Ask for all the information about so and so
declare sid number;
sname emp.ename%type;
sjob emp.job%type;
begin
sid:=7369;
select ename,job into sname,sjob from emp where empno=sid;
dbms_output.put_line(sname||' '||sjob);
end;
Of course , If there are many columns in the table , Do you still write like this ?
NO, Use row type :%rowtype;-- Query all the information about so and so
declare sid number;
er emp%rowtype;
begin
sid:=7369;
select * into er from emp where empno=sid;
dbms_output.put_line(er.ename||' '||er.job);
end;
============================================Input :& ( Generally used for testing , Not much use in other cases )
declare sid number;
er emp%rowtype;
begin
sid:=& Please enter ; --& similar scanner
select * into er from emp where empno=sid;
dbms_output.put_line(er.ename||' '||er.job);
end;Be careful :sid:=& Please enter ; -- Represents that the input is an integer
sid:='& Please enter '; -- On behalf of the input is varchar2 type .
=======================================
Logical comparison :
<> , !========================================
Control statement :
if Conditions then
……
else perhaps elsif…then
……
end if-- Wages are greater than 3500 pay taxes ,=3500 just ,<3500 Strive
if sentence :
begin
if sal>3500 then
dbms_output.put_line(' pay taxes ');
elsif sal=3500 then
dbms_output.put_line(' just ');
else
dbms_output.put_line(' Strive ');
end if;
end;
case sentence :
case
when then ;
when then ;
else
end case;Loop statement : There are three kinds of :
1.loop An unconditional cycle
2.while
3.for-- Print 1~100
declare i number;
begin
i:=1;
loop
dbms_output.put_line(i);
i:=i+1;
exit when i=100; -- Exit and exit conditions
end loop;
end;
============================================
declare i number;
begin
i:=1;
<<b_loop>> --loop The name of the loop
loop
dbms_output.put_line(i);
i:=i+1;
exit b_loop when i=100; -- Exit and exit conditions
end loop;
end;
==========================================
-- seek 1~100 And
declare i number;
mysum number;
begin
i:=0;
mysum:=0;
while i<=100 loop
mysum:=mysum+i;
i:=i+1;
end loop;
dbms_output.put_line(' The sum of the :'||mysum);
end;
-- It will be used in the loop loop--for The cycle of writing :
declare
mysum number;
begin
mysum:=0;
for i in 1..100 loop
mysum:=mysum+i;
end loop;
dbms_output.put_line(mysum);
end;
-- Find the sum of odd numbers
declare
mysum number;
begin
mysum:=0;
for i in 1..100 loop
if mod(i,2)=1 then
mysum:=mysum+i;
end if;
end loop;
dbms_output.put_line(mysum);
end;
-- Sequential statements :goto Label ……<< Label >>
Don't speak , A: no, no .======================================
abnormal :
1. System built-in exception --- Predefined exceptions
2. We write the exception of the codegram --- Custom exception1. Predefined exceptions
too_many_rows : Too much
no_data_found : Data not foundExample : Predefined exceptions :
declare sid number;
shiredate emp.hiredate%type;
sb shiredate%type;
begin
sid:=7369;
select hiredate into shiredate from emp;
dbms_output.put_line(shiredate);
-- abnormal
exception -- If an exception occurs, an error will be reported
when too_many_rows then
dbms_output.put_line(' Too much ');
end;Example : Custom exception
The three step : Statement , Judge , captureiee exception;
raise iee;
exception when iee then
dbms_output.put_line(' error message ');
when too_many_rows then
dbms_output.put_line(' error message ');
……Multiple exception bodies can be carried
===============================================
function :
create or replace function f_name [( Parameters 1, Parameters 2..)]
return type
is/as
[local declarations] -- The variable declaration in the function body is placed in this positionbegin
-- Executor
return
-- abnormal
end;
-- Case study : Number , Return salary ' pay taxes ' still ' just ', still ' Strive '
create or replace function f_n126(sid number)
return varchar2
isssal number(8,2);
str varchar2(22); -- Be careful , There is no need to declare Definitionbegin
select sal into ssal from emp where empno=sid;
if ssal>3500 then
str:=' pay taxes ';
elsif ssal=3500 then
str:=' just ';
else
str:=' Strive ';
end if;
return str;
end;-- How to call a function ?
--oracle Call mode :
select f_n126(7369) from dual;
--pl/sql Call mode :
declare str varchar2(22);
begin
str:=f_n126(7369);
dbms_output.put_line(str);
end;====== Custom exception =========================================
declare n_s number(5);
e_my exception;
pragma exception_init(e_my,-20001);
begin
select count(stuname) into n_s from stuinfo where stuname like ' Zhao %';
if n_s=0 then
raise e_my;
end if;
dbms_output.put_line(' The number is '||n_s);exception
when e_my then
dbms_output.put_line(' Personnel is empty ');
end;
===== function =================================================
create or replace function my_temp(n_s in varchar2, n_max in out number)
return number is
n_tavg number(5, 2);
begin
select avg(stuage),max(stuage) into n_tavg,n_max from stuinfo where stuname like n_s||'%';
return n_tavg;
end;create or replace function my_sum(n_a in number)
return number
is
n_sum number(5):=0;
beginfor int_s in 1..n_a loop
n_sum:=n_sum+int_s;
end loop;
return n_sum;
end;
Demonstrate basic usage
--oracle-03 Built in functions
-- Conversion function :to_date to_char to_number
-- Date function :sysdate|systimestamp|add_months|months_between|extract(year from sysdate)|last_day|next_day|round|trunc
-- String function :lower|upper|ltrim|rtrim|lpad|rpad|chr|ascii|instr|substr|replace|decode|length
-- Mathematical functions :abs|round|trunc|sign|mod|power|sqrt|ceil|floor
-----------------------------------------------------------------------
--oracle-04 PL/SQL Programming
1.pl: Process language
2.sql: Structured query language
3.pl/sql It is the combination of process language and structured query language .sql What language can achieve pl/sql Can also be realized .
4.pl/sql What technologies are included in programming ?
Printout , Variable usage , Selection structure , Loop structure
5.pl/sql Combine : Three part combination
(1) Statement ( Definition ) part
(2) The executable part
(3) Exception handling part ( In the executable part of the package )
The second module is required , And the first and third are optional ( According to demand )
6. grammar
declare-- Declaration part
Property name Attribute types ;
....
begin--- The starting position of the executable part
utilize sql The result set obtained by the execution of the statement can assign the result to the above in a specific way declare In the defined variables .
Exception handling part
end;--- The end of the executable
select sal from emp where empno = 7369;
-- demand : adopt PL/SQL Program printout "zz is a nice man"
-- Printout :dbms_output.put_line();---》 Sources and oracle Built in packages in
begin
dbms_output.put_line('zz is a nice man');
end;
-- Define a variable to hold a name , Then print out
declare
sname varchar2(50);
begin
-- The assignment of a variable :=
sname := ' Zhang San ';
dbms_output.put_line(sname);
end;
-----------------------------------------------
declare
sname varchar2(50):=' rees ';
begin
dbms_output.put_line(sname);
end;
-----------------------------------------------
-- Define multiple variables
declare
sname varchar2(50):=' rees ';
ssex varchar2(2):=' male ';
begin
dbms_output.put_line(' My name is :'||sname||', My gender is : '||ssex);
end;
--oracle Input device in & Wrapped in single quotation marks .
declare
sname varchar2(50):='& Please enter ';
ssex varchar2(2):=' male ';
begin
dbms_output.put_line(' My name is :'||sname||', My gender is : '||ssex);
end;
-- Printout 7499 's salary .
declare
myempno number:=7499;
mysal number;
begin
-- grammar : select aa into bb from surface
select sal into mysal from emp where empno = myempno;
dbms_output.put_line(' The salary is : '||mysal);
end;
-- Printout 7369 Your name and salary
declare
myempno number:=7369;
myename varchar2(100);
mysal number;
begin
-- grammar : select aa into bb from surface
select ename,sal into myename,mysal from emp where empno = myempno;
dbms_output.put_line(' The salary is : '||mysal||' '||myename);
end;
-----------------------------------------------------------------
PL/SQL Programming 2 There are two important types
Attribute types %type
Line type %rowtype amount to oop The object of
-- Printout 7369 's salary ( Uncertain type )
declare
myempno emp.empno%type:=7369; ------- emp.empno%type => number
mysal emp.sal%type;
begin
select sal into mysal from emp where empno = myempno;
dbms_output.put_line(mysal);
end;
-- Printout 7369 All properties of
declare
myempno emp.empno%type:=7369; ------- emp.empno%type => number
myemp emp%rowtype;
begin
select * into myemp from emp where empno = myempno;
dbms_output.put_line(myemp.empno||' '||myemp.ename||' '||myemp.sal);
end;
-------------------------------------------------------------
# Selection structure if case
-- demand : Determine whether a number is even
declare
mynum number:=10;
begin
if (mod(mynum,2)=0) then
dbms_output.put_line(' even numbers ');
else
dbms_output.put_line(' Odd number ');
end if;-- End selection structure
end;
-->3000 tax =3000 Continue to work hard <3000 Go home and raise pigs
select ename,sal,
decode(sign(sal-3000),'1',' tax ','0',' Continue to work hard ','-1',' Go home and raise pigs ')
from emp;
-- No learning cursor ( Courseware ) Only one... Can be queried
-- Judge 7369 At what level
declare
myempno emp.empno%type:=7369;
mysal emp.sal%type;
begin
select sal into mysal from emp where empno = myempno;
-- Get mysal Just judge
if (mysal > 3000) then
dbms_output.put_line(' tax ');
elsif (mysal = 3000) then
dbms_output.put_line(' Continue to work hard ');
elsif(mysal < 3000) then
dbms_output.put_line(' Go home and raise pigs ');
end if;
end;
--case end case
begin
case 'F'
when 'A' then dbms_output.put_line(' good ');
when 'B' then dbms_output.put_line(' good ');
when 'C' then dbms_output.put_line(' commonly ');
when 'D' then dbms_output.put_line(' Okay ');
else
dbms_output.put_line('LOW');
end case;
end;
------------------------------------------------------
--loop while for
--loop loop
/*
loop
end loop;
And java Consistent with the dead cycle in while(true){}
*/
declare
mynum number:=1;
begin
loop
dbms_output.put_line(mynum);--99
mynum:=mynum+1;
exit when mynum = 101;
end loop;
end;
--1-100 And
declare
mynum number:=1;
mysum number:=0;
begin
loop
mysum:=mysum + mynum;
mynum:=mynum+1;
exit when mynum = 101;
end loop;
DBMS_OUTPUT.PUT_LINE(mysum);
end;
-- name
declare
mynum number:=1;
mysum number:=0;
begin
<<myloop>>
loop
mysum:=mysum + mynum;
mynum:=mynum+1;
exit when mynum = 101;
end loop;
DBMS_OUTPUT.PUT_LINE(mysum);
end;
--while loop
declare
mynum number:=1;
begin
while (mynum<=100) loop
dbms_output.put_line(mynum);
mynum:=mynum+1;
end loop;
end;
--for The cycle is the simplest
begin
for i in 1..100 loop
dbms_output.put_line(i);
end loop;
end;
-- abnormal
1. Default meaning exception : System given no_data_found( No data exception found ) too_many_rows( There are too many exceptions )
2. Custom exception :raise Throw an exception
(1) Define custom exceptions exception
(2) Throw an exception after judging according to the requirements raise
(3) Catch the exception exception
declare
myempno number:=123;
mysal number;
begin
-- grammar : select aa into bb from surface
select sal into mysal from emp where empno = myempno;
dbms_output.put_line(' The salary is : '||mysal);
exception
when no_data_found then
dbms_output.put_line(' No data exception found ( The number provided does not exist )');
end;
--------------------
declare
mysal number;
begin
-- grammar : select aa into bb from surface
select sal into mysal from emp;
dbms_output.put_line(' The salary is : '||mysal);
exception
when too_many_rows then
dbms_output.put_line(' There are too many exceptions ');
when no_data_found then
dbms_output.put_line(' No data exception found ');
end;
-- Query the salary of the specified number , If not 2000-5000 Between , Throw custom exception
declare
myempno emp.empno%type:=7369;
mysal emp.sal%type;
myExceptionSal exception;
begin
select sal into mysal from emp where empno = myempno;
if (mysal < 2000 or mysal > 5000) then
-- Throw an exception
raise myExceptionSal;
end if;
exception
when myExceptionSal then
dbms_output.put_line(' The unpaid salary is not within the specified range. Exception ');
end;
------------------------------------------------------------------
-- function function effect : One package, multiple uses
/*
public void add(){
}
create or replace function The name of the function ( parameter list )
return Return type
as|is
Declaration part
The executable part
*/
-- Packaging function Find salary based on the specified number
create or replace function getSalById(myempno emp.empno%type)
return emp.sal%type
as
mysal emp.sal%type:=0;
begin
select sal into mysal from emp where empno = myempno;
return mysal;
end;
-- Call function
select getSalById(7369) from dual;
--1-100 And
create or replace function mySum(mynum number)
return number
as
sums number:=0;
begin
for i in 1..mynum loop
sums:=sums + i;
end loop;
return sums;
end;
select mySum(10) from dual;
-- Recursive implementation of Fibonacci sequence No 21 The number of the item
-- 1 1 2 3 5 8 13 21 .......
create or replace function diGuiDemo(mynum number)--3 diGuiDemo(1)+diGuiDemo(2)
return number
as
begin
if( mynum = 1 or mynum = 2) then
return 1;
else
return diGuiDemo(mynum-1)+diGuiDemo(mynum-2);
end if;
end;
select diGuiDemo(21) from dual;
边栏推荐
- Druid query
- Doris' table creation and data division
- Summary of the latest rail transit (Subway + bus) stops and routes in key cities in China (II)
- An error is reported in the JDBC connection database: connection to 139.9.130.37:15400 referred
- Get to know druid IO real time OLAP data analysis storage system
- Dish recommendation system based on graph database
- MySQL group commit
- Use of file class
- Data from the first to seventh census (to counties)
- Understand the difference between reducebykey and groupbykey in spark
猜你喜欢
Peking University HP financial index - matching enterprise green innovation index 2011-2020: enterprise name, year, industry classification and other multi indicator data
Brief introduction: distributed cap theory and base theory
LVS四层负载均衡集群(5)LVS概述
A data modeling optimization solution for graph data super nodes
[azure data platform] ETL tool (4) - azure data factory debug pipeline
MySQL transaction isolation level experiment
简述:分布式CAP理论和BASE理论
Aggregation analysis of research word association based on graph data
MASA Auth - 从用户的角度看整体设计
Sparksql of spark
随机推荐
English grammar_ Frequency adverb
Watering artifact based on Huawei cloud Internet of things (stm32+esp8266)
Use of compact, extract and list functions in PHP
Summary of the latest rail transit (Subway + bus) stops and routes in key cities in China (II)
Spark optimization - data skew solution
Simulink代码生成: 简单状态机及其代码
PostgreSQL common SQL
MySQL learning summary XIII: detailed explanation of if, case, loop, while & cursor of process control
Coal industry database - coal price, consumption, power generation & Provincial Civil and industrial power consumption data
MySQL learning summary 7: create and manage databases, create tables, modify tables, and delete tables
Explode and implode in PHP
Doris data aggregation
Simulink code generation: table lookup module and its code
Local simulation download file
Solve the error in CONDA installation PyMOL
MySQL imports and exports multiple libraries at one time
[synchronization function] version 2.0.16-19 has the update of synchronization function repair, but the problem has not been solved
MySQL transaction isolation level experiment
[azure data platform] ETL tool (7) - detailed explanation of ADF copy data
LVS four layer load balancing cluster (6) LVS working mode