PL/SQL學習總結(1)
阿新 • • 發佈:2019-01-04
PL/SQL是一種面向過程的類似Pascal的語言,是Oracle公司對SQL語言的功能的擴充套件,它是將過程性結構與oracle SQL無縫的整合在一起而產生的一種結構化的強有力的語言,是一種高階資料庫程式設計語言。
1、程式開始
一個完整的程式體
if判斷
declare --宣告變數 變數名 型別
a number:=5 ; --宣告時賦值
b number:=2;
c number;
--在plsql中可以使用SQL裡面的型別以保證型別一致
-- user_name user.user_name%type;--該變數與資料庫user表中user_name欄位屬性一致
begin ---- 程式開始
if a>0 and b>0 then -- if條件
c:=a+b; --賦值操作使用:=
elsif a<0 and b>0 then
c:=a*b;
else
c:=a-b;
dbms_output.pput_line(c) ; --控制檯輸出
end if;---一定要end if
exception when others then --異常的捕獲
dbms_output.pput_line('error') ;
end;
2、迴圈控制語句
declare
a number;
begin
for i in 1..3 loop
dbms_output.pput_line(i) ;
end loop;--end loop 不能少
exception when others then
dbms_output.pput_line('error') ;
end;
輸出結果
因為plsql是一門增強的SQL語言,所以,plsql可以直接用for迴圈遍歷SQL語句查詢出來的結果(遍歷遊標)
declare
begin
for emp in (select * from employees e where e.employee_id<110 ) loop
dbms_output.put_line('id: '||emp.employee_id||'fname: '||emp.first_name) ;
end loop;
exception when others then
dbms_output.pput_line('error') ;
end;
結果如下:
3、plsql中陣列的定義
在plsql中並沒有嚴格的陣列這個定義,我們可以將陣列理解成為一個表,每條記錄相當於陣列的一行,多少條記錄就有多少行,在plsql中有兩種型別,table和record,table只能裝一列,而record只能裝一行多列,實現陣列可以在table裡面裝record,兩者結合就是一個數組
--這裡以hr下的employees表為例
declare
ind number:=1;
type type_record is record(
ename employees.first_name%type,
eemail employees.email%type,
esalary employees.salary%type
); ---到這裡就定義出了一條記錄型別,三個欄位分別是ename,eemail,esalary;
my_record type_record; --這個地方是宣告一個my_record變數是_record 型別
type type_table is table of type_record index by binary_integer;
--定義一個table型別,該型別裡面只能儲存_record型別的記錄 ,int索引
my_table type_table;--宣告my_table變數為_table型別;
begin
for emp in(select e.first_name,e.email,e.salary
from employees e where e.employee_id <110) loop
--為記錄賦值
my_record.ename:=emp.first_name;
my_record.eemail:=emp.email;
my_record.esalary:=emp.salary;
--將記錄存到table裡面
my_table(ind):=my_record;
ind:=ind+1;
end loop;------------------迴圈存資料
---------------迴圈輸出資料
for i in 1..my_table.count loop
dbms_output.put_line('employee_name: ' || my_table(i).ename || ' ' || 'email: ' ||
my_table(i).eemail || 'salary: ' || my_table(i).esalary );
end loop;
exception when others then
dbms_output.put_line('error');
end;
輸出結果如下
嗯。。暫時就先想到這麼多,後面的想到了再寫 。