set serverout on;
declare cursor cu_patientinfo is
select hpb.patient_name,to_char(hpb.birthday),hpb.sex,to_char(hpv.datetime_in) from his_patient_base hpb inner join his_patient_visit hpv on hpv.patient_id=hpb.patient_id where rownum<100 ;
patient_name varchar2(20);
birthday varchar2(40) ;
sex varchar2(8);
datetime_in varchar2(40);
begin
open cu_patientinfo;
fetch cu_patientinfo into patient_name,birthday,sex,datetime_in ;
while cu_patientinfo%found loop
dbms_output.put_line('我叫'||patient_name||':'||birthday||'出生,性別:'||sex||'生病時間爲 :'||datetime_in);
fetch cu_patientinfo into patient_name,birthday,sex,datetime_in;
end loop;
close cu_patientinfo;
end;
--2 使用行變量
declare cursor cur_return is
select * from his_patient_base where rownum<10;
infoa his_patient_base%rowtype;
begin
open cur_return ;
fetch cur_return into infoa ;
while cur_return%found loop
dbms_output.put_line(infoa.patient_name);
fetch cur_return into infoa;
end loop;
close cur_return;
end;
---3 有參數的遊標
declare cursor cur_return(rowopertor number) is
select * from his_patient_base where rownum<rowopertor;
employees his_patient_base%rowtype;
i number :=0;
begin
open cur_return(4);
fetch cur_return into employees ;
while cur_return%found loop
i := i+1;
dbms_output.put_line(employees.patient_name||i);
fetch cur_return into employees;
end loop;
close cur_return;
end;
---------隱式遊標的默認爲內置遊標
--案例1
begin
if sql%isopen then
dbms_output.put_line('sql遊標一打開');
else
dbms_output.put_line('sql遊標未打開');
end if;
dbms_output.put_line('遊標獲取記錄數'||sql%rowcount);
end;
---------有影響的隱式遊標
declare patient_count varchar2(20) ;
begin
select patient_id into patient_count from his_patient_base where rownum<2;
if sql%isopen
then dbms_output.put_line('遊標一打開');
else
dbms_output.put_line('遊標未開');
end if;
dbms_output.put_line('返回受影響的行數'||sql%rowcount);
end ;
---------------
---------------cursor for(隱式遊標) 遊標的使用
--不用聲明遊標變量和打開
begin
for employee in (select * from his_patient_visit where rownum<5)loop
dbms_output.put_line(employee.patient_id|| ':'||employee.datetime_in);
end loop;
end;
--------
顯示遊標麻煩但 靈活 ;隱式遊標簡練 使用於簡單的;
動態遊標: 強類型遊標和弱類型遊標;
強類型遊標的定義: 在使用之前未指定sql查詢定義;但類型以確定;
弱類型遊標 : 當不確定返回類型是選擇
語法: type name is ref cousor;