PL SQL 程式設計

2022-09-20 00:27:13 字數 2656 閱讀 5064

pl/sql 程式結構:

declare

宣告部分(宣告變數、型別、游標以及布局的儲存過程及函式)

begin

執行部分(過程及sql語句,程式的主要部分,是必須的)

end;

eg(基表為course):

declare

v_cno varchar(20) :='001';

begin

select * from course where cno=v_cno;

delete * from course where cno=v_cno;

end;

------查詢course表中cno=『001』的資料

------刪除course表中cno=『001』的資料

returning的使用

在需要返回dml語句執行後的資訊時使用,講個例子加以說明

本例基表為student(sno, sname, classno)

declare

s_no varchar2(20);

s_name varchar2(40);

begin

insert into student values('20110001','張三','051')  returning sno,sname into s_no, s_name;

dbms_output.put_line(s_no);

dbms_output.put_line(s_name);

end------將插入的資訊之中的sno、sname對應的賦值給s_no,s_name

type、%type的使用

type 用於定義類,具體用例子說明

基表為course(cno,cname,credit)

declare

type c_rec is record(

c_cno char(10):=&no,

c_cname char(40)

);rec_course c_rec;              -------rec_course 的型別為c_rec類

begin

select cno,cname into rec_course from course where cno=rec_course.c_cno;

dbms_output.put_line(rec_course.c_cno||'     '||rec_course.c_cname);

end;

declare

type c_rec is record(

c_cno course.cno%type:=&no,            --c_cno引用了course表中的cno的資料型別和寬度

c_cname course.cname%type);           --c_cname引用了course表中cname的資料型別和寬度

rec_course c_rec;

begin

select cno,cname into rec_course from course where cno=rec_course.c_cno ;

bdms_output.put_line(rec_course.c_cno||'    '||rec_course.c_cname);

end;

上例中的『&no』表示使用者自行輸入的資料作為c_cno的預設值

%rowtype返回乙個記錄型別,例如:

declare

c_cno course.cno%type:=&no;

rec_course course%rowtype;                

begin

select * into rec_course from course where cno=c_cno;   

----rec_course中引用了course表中滿足條件的一行資料

dbms_output.put_line(『課程名:』||rec_course.cname||'  課程號: '||rec_course.cno);

end;

表型別declare

type table_type_name is table of table_name%rowtypeindex by binary_integer;

.......

begin

.......

end;

其中:table_type_name 是表型別的名稱,table_name 是參照表的名稱,is table 表示該型別為表型別

eg:declare

type sc_table is table of sc%rowtype index by binary_integer;

w_sc sc_table;

begin

select sno,cno,grade into w_sc(1).sno,w_sc(1).cno,w_sc(1).grade  from sc where sno='20110002' ;

dbms_output.put_line(w_sc(1).sno||' '||w_sc(1).cno||' '||w_sc(1).grade);

end;

注意:表型別的賦值不能直接賦值給表物件,即 select  *  into  w_sc  from sc where sno='20110001'; 這樣複製是錯誤的,應該使用下標,如以上的示例

PLSQL程式設計

create table emomy1 emon varchar2 100 time1 date drop table emomy1 select from emomy1 begin dbms output.put line hello,world end 定義變數 declare name con...

PL SQL程式設計

1.具有程式語言的特點,他能把一組sql語句放到乙個模組中,使去更具有模組的程式的特點 2.採用過程性語言控制程式的結構,也就是說,在pl sql中增強邏輯結構,如迴圈,判斷等程式結構 3.pl sql可以對程式中的錯誤進行自動處理,使程式能夠在遇到錯誤時不會中斷,及他的處理異常機制 4.具有更好的...

PL SQL程式設計基礎 PL SQL簡介

課程教師 李興華 課程學習者 陽光羅諾 日期 2018 07 28 知識點 1 了解pl sql的主要特點 2 掌握pl sql塊的基本結構 pl sql語法結構 語法 declare 宣告部分,例如。定義變數 常量 游標。begin 程式編寫 sql語句 exeception 處理異常 end 說...