韓順平玩轉oracle之pl sql聽課筆記《三》

2021-08-27 00:25:09 字數 2638 閱讀 3857

有些慚愧,距離第2次聽課筆記遠了。這一講主要是關於函式,包,還有變數的解釋。

1 函式和過程的區別

1)函式:返回特定值,通常是乙個;

過程:執行特定操作

2)建立函式時:

在函式頭須包含return子句

例如;return number is

think_salary number(7,2)

在函式體也須包含return語句

return think_salary

2 案例:輸入雇員的姓名,返回該雇員的年薪

create function sp_think(spname varchar2)

return number is

yearsal number(7,2);

begin

select sal*12+nvl(comm,0)*12 into yearsal from emp where ename=spname;

return yearsal;

end;

/在sqlplus中呼叫:

var think number

call sp_think('scott') into:think

print think

3 包用於邏輯上組合過程和函式,由包頭和包體組成,其中

包頭:對過程或函式的宣告

包體:實現包頭中所宣告的過程或函式

案例:包頭:

create package sp_think

isprocedure update_sal(name varchar2,newsal number);

function annual_income(name varchar2) return number;

end;

/包體:

create package body sp_think is

procedure update_sal(name varchar2,newsal number)

isbegin

update emp set sal=newsal where ename=name;

end;

function annual_income(name varchar2)

return number is

annual_salary number;

begin

select sal*12+nvl(comm,0) into annual_salary from emp where ename=name;

return annual_salary;

end;

end;

/4 如何呼叫包的過程或函式

呼叫自己建立的包時:

call sp_think.update_sal('scott',1500);

呼叫其他方案的包時,如hr:

call hr.sp_think.update_sal('scott',1500);

5 觸發器

觸發器是自動執行的過程

包含:1)觸發的事件:如dml語句

2)觸發的操作:pl/sql塊

作用:維護資料庫的安全和一致性

6 變數

1)v_ename varchar2(10) -- :=為賦值號,如v_sal number(6,2):=5.8

2)用於存放多值的變數:

2.1) pl/sql記錄:同c語言的結構體相似

案例:declare

type think is record(name emp.ename%type,salary emp.sal%type)--name隨ename的變而變

re_think think

begin

select ename,sal into think from emp where empno7788;

dbms_output.put_line('員工名:'||think.name);

end;

2.2)pl/sql表:同c語言的陣列相似

案例:declare

type think is table of emp.ename%type index by binary_integer;

-- 定義了乙個pl/sql表型別,存放emp.ename%type,下標是正整數

ta_think think;

....

3) 游標變數:結果集的指標

案例:定義乙個pl/sql塊,可以輸入部門號,顯示該部門所有員工的姓名和工資

declare

type think_cursor is ref cursor;

water_cursor think_cursor;

v_ename emp.ename%type;

v_sal emp.sal%type;

begin

open water_cursor for select ename,sal from emp where deptno=&a;

loop

fetch water_cursor into v_ename,v_sal;

exit when water_cursor%notfound;

dbms_output.put_line('名字:'||v_ename||'工資:'||v_sal)

end loop

end;

韓順平 玩轉oracle 角色

connect角色 具有一般應用開發人員需要的大部分許可權 具有的系統許可權 alter session create cluster create database link create session create table create view create sequence resou...

韓順平玩轉oracle之pl sql聽課筆記《三》

有些慚愧,距離第2次聽課筆記遠了。這一講主要是關於函式,包,還有變數的解釋。1 函式和過程的區別 1 函式 返回特定值,通常是乙個 過程 執行特定操作 2 建立函式時 在函式頭須包含return子句 例如 return number is think salary number 7,2 在函式體也須...

韓順平玩轉oracle之pl sql聽課筆記《三》

有些慚愧,距離第2次聽課筆記遠了。這一講主要是關於函式,包,還有變數的解釋。1 函式和過程的區別 1 函式 返回特定值,通常是乙個 過程 執行特定操作 2 建立函式時 在函式頭須包含return子句 例如 return number is think salary number 7,2 在函式體也須...