plsql learning

plsql (procedure language sql) structured sql statement.

1. The concept of blocks:

It is the smallest execution unit of plsql, which consists of declear, begin, exception, and end.

DECLARE
--Declaration part (mainly declare variables, constants, cursors, etc.), this part can be omitted
BEGIN
--Execution part, this cannot be missing
EXCEPTION
--The exception part, this part is to capture the exception in this place during the previous execution, you can not
END;

 E.g:

declare
v_ename varchar2(10);
v_sal number (7,2);
begin
select ename,sal into v_ename,v_sal from emp where empno=&aa;
dbms_output.put_line(v_ename || '  ' || v_sal);
exception
when no_data_found then
dbms_output.put_line('wrong number!');
end;

 ----set serveroutput on open pl/sql developer to display the information output by dbms_output.put_line;

2. Stored procedure

component:

create procedure procedure_name
is
-- variable declaration
begin
-- execute code
end;

 E.g:

create procedure po_pro2(spEmpno number,spSal number)
is
begin
update emp set sal=spSal where empno=spEmpno;
end;

 Example 2: A stored procedure with no return value (add a record to the emp table through a stored procedure);

create procedure insert_pro(
spNo in number,
spName in varchar2,
spSal in number,
spJob in varchar2,
spDeptno in number)
is
begin
insert into emp(empno,ename,sal,job,deptno) values(spNo,spName,spSal,spJob,spDeptno);
end;

 Corresponding java call:

Class.forName("oracle.jdbc.driver.OracleDriver");
			
			Connection conn = DriverManager.getConnection("jdbc:oracle:thin:@127.0.0.1:1521:orcl", "scott", "a123");
			
			CallableStatement cs = conn.prepareCall("{call insert_pro(?,?,?,?,?)}");
			
			cs.setInt(1, 71);
			cs.setString(2, "mickey");
			cs.setInt(3, 1001);
			cs.setString(4, "CLECK");
			cs.setInt(5, 10);
			cs.execute();

 Example 3: Stored procedure with return value (queries the name, salary, etc. of the user whose emp table empno is 7788)

create procedure getName_pro(
spNo in number,
spName out varchar2,
spSal out number
)
is
begin
select ename,sal into spName,spSal from emp where empno=spNo;
end;

 The corresponding java call:

CallableStatement cs = conn.prepareCall("{call getName_pro(?,?,?)}");
			
			cs.setInt(1, 7788);
			cs.registerOutParameter(2, OracleTypes.VARCHAR);
			cs.registerOutParameter(3, OracleTypes.FLOAT);
			cs.execute();
			
			String name = cs.getString(2);
			Float sal = cs.getFloat(3);
			
			System.out.println("Name:"+name+"salary:"+sal);

 The second case: a call to a stored procedure that returns a result set (queries the names and salaries of all users in a department in the emp table)

--Create a package to store the result set

create package pac_test1 as
type my_cursor is ref cursor;
end pac_test1;

 -- create stored procedure

create procedure pro_test3(spNo in number,sp_cursor out pac_test1.my_cursor)
is
begin
    open sp_cursor for select * from emp where deptno=spNo;
end;

 --Corresponding to the call in java:

CallableStatement cs = conn.prepareCall("{call pro_test3(?,?)}");
			cs.setInt(1, 20);
			cs.registerOutParameter(2, OracleTypes.CURSOR);
			
			cs.execute();
			
			ResultSet rs = (ResultSet)cs.getObject(2);
			while(rs.next()) {
				System.out.println(rs.getString("ename") + "--" +rs.getString("sal"));
			}

 Example 4: Stored procedure writes a simple paging

--Create a paginated package

create package fenye_pac as
type fenye_cursor is ref cursor;
end fenye_pac;

 --Create a stored procedure, this paging only realizes the paging of the entire table to obtain the data of the current page that meets the conditions and display the total number of pages and total records .

create or replace procedure pro_test4(
tableName in varchar2,   --表名
pageCount in number, -- the number of records per page
currentPage in number, -- the content of which page is needed
totalCount out number, -- total number of records
totalPage out number, --total number of pages
p_cursor out fenye_pac.fenye_cursor -- store the returned result set
)
is
v_sql varchar2(1000);
v_start number;
v_end number;
begin
--Calculate pagination start value
v_start:=(currentPage-1)*pageCount;
--Calculate pagination end value
v_end:=currentPage*pageCount;
v_sql:='select * from (select rownum r,e.* from '|| tableName ||' e where rownum<='|| v_end ||') where r>'|| v_start;
open p_cursor for v_sql;
-- get the total number of records
v_sql:='select count(1) from '|| tableName;
execute immediate v_sql into totalCount;
-- Calculate the total number of pages
if mod(totalCount,pageCount) = 0 then
totalPage:=totalCount/pageCount;
else
totalPage:=totalCount/pageCount+1;
end if;
end;

 The corresponding java invocation method:

CallableStatement cs = conn.prepareCall("{call pro_test4(?,?,?,?,?,?)}");
			cs.setString(1, "emp");
			cs.setInt(2, 5);
			cs.setInt(3, 2);
			cs.registerOutParameter(4, OracleTypes.INTEGER);
			cs.registerOutParameter(5, OracleTypes.INTEGER);
			cs.registerOutParameter(6, OracleTypes.CURSOR);
			
			cs.execute();
			int totalCount = cs.getInt (4);
			int totalPage = cs.getInt(5);
			ResultSet rs = (ResultSet)cs.getObject(6);
			System.out.println("Total pages:"+totalPage+"--Total records:"+totalCount);
			while(rs.next()) {
				System.out.println(rs.getString("ename") + "--" + rs.getString("sal"));
			}

 3. Creation of the function:

Example 1: Calculate the annual salary of an employee;

 

create or replace function fun_test1(spNo number)
return number is yearSal number(7,2);
begin
select sal*12 into yearSal from emp where empno=spNo;
return yearSal;
end;

Ways to test a function in pl/sql:

var yearSal number;
call fun_test1(7788) into:yearSal;

 4. Package:

Including: procedures, functions, variables, constants, types, exceptions, cursors.

Example 1:

-- package declaration
create or replace package pac_test1 as
--Declaration of constants
c_pi number:=3;
-- public type
type t_rec is record(m1 number,m2 varchar2(10));
-- public variable
v_rec t_rec;
--procedure statement
procedure select_name(spNo in number);
-- function declaration
function count_sal(spNo in number) return number;
end pac_test1;

 

-- Implementation of the package body
create or replace package body pac_test1 is
procedure select_name(spNo in number)
is
spName emp.ename%type;
begin
select ename into spName from emp where empno=spNo;
dbms_output.put_line(spName);
end;
function count_sal(spNo in number) return number is yearSal number(7,2);
begin
select sal*12 into yearSal from emp where empno=spNo;
return yearSal;
end;
end pac_test1;

 5.plsql type:

Three common types in plsql: scalar type, composite type, parameter type

(1). Scalar types: some relatively simple types, such as number, varchar2, date and so on.

            Note: When declaring a scalar type variable, if you are not sure about the specific type of the variable, you can determine the type through the field %type in the table

            E.g:

DECLARE
     v_name emp.ename%type;
     v_sal number (7,2);
BEGIN
     select ename,sal into v_name,v_sal from emp where empno=&no;
END;

(2). Composite type: It is a combination of several scalar types. For example, a row of data in a table can be regarded as a composite type. At this time, the type can be determined by %rowtype

for example:

declare
v_row_emp emp%rowtype;
begin
select * into v_row_emp from emp where empno=7788;
dbms_output.put_line(v_row_emp.ename);
end;
Declare a composite type by yourself. For example, when you don't need all types of data in a row in a table in some cases, you need to define those required types yourself, as follows:
declare
type my_type is record(v_name emp.ename%type,v_sal emp.sal%type);
v_row_emp my_type;
begin
select ename,sal into v_row_emp from emp where empno=7788;
dbms_output.put_line(v_row_emp.v_name);
end;
 (3). Parameter type: If the type of the obtained data is not only one row of data, but multiple rows of data, then the parameter type (cursor) is required at this time; the specific examples are as follows:
declare
cursor my_cursor
is select * from emp where deptno=10;
v_cursor my_cursor%rowtype;
begin
open my_cursor;
loop
fetch my_cursor into v_cursor;
exit when my_cursor%NOTFOUND;
dbms_output.put_line(v_cursor.ename);
end loop;
end;
 

Guess you like

Origin http://10.200.1.11:23101/article/api/json?id=326725057&siteId=291194637