游標 游標的簡介:
逐行處理查詢結果,以編程的方式訪問數據
游標的類型:
1,隱式游標:在 PL/SQL 程序中執行DML SQL 語句時自動創建隱式游標,名字固定叫sql。
2,顯式游標:顯式游標用於處理返回多行的查詢。
3,REF 游標:REF 游標用於處理運行時才能確定的動態 SQL 查詢的結果
隱式游標:
q在PL/SQL中使用DML語句時自動創建隱式游標 q隱式游標自動聲明、打開和關閉,其名為 SQL q通過檢查隱式游標的屬性可以獲得最近執行的DML 語句的信息 q隱式游標的屬性有: q%FOUND – SQL 語句影響了一行或多行時為 TRUE q%NOTFOUND – SQL 語句沒有影響任何行時為TRUE q%ROWCOUNT – SQL 語句影響的行數 q%ISOPEN - 游標是否打開,始終為FALSE
|
在select中有兩個中比較常見的異常: 1. NO_DATA_FOUND 2. TOO_MANY_ROWS
|
顯式游標:
sqlserver與oracle的不同之處在於: 最后sqlserver會deallocate 丟棄游標,而oracle只有前面四步: 聲明游標、打開游標、使用游標讀取記錄、關閉游標。
顯式游標的使用:
|
REF游標也叫動態游標:
qREF 游標和游標變量用於處理運行時動態執行的 SQL 查詢 q創建游標變量需要兩個步驟: q聲明 REF 游標類型 q聲明 REF 游標類型的變量 q用於聲明 REF 游標類型的語法為:
TYPE <ref_cursor_name> IS REF CURSOR
[RETURN <return_type>];
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
|
-----------------------------------ref游標---------------------------------
declare
type ref_cursor is ref cursor; --聲明一個ref游標類型
tab_cursor ref_cursor ;--聲明一個ref游標
sname student.xm %type ;
sno student.xh %type ;
tab_name varchar2 (
20
);
begin
tab_name :=
'&tab_name'
; --接收客戶輸入的表明
if
tab_name =
'student'
then
open tab_cursor
for
select xh ,xm from student ; --打開ref游標
fetch tab_cursor into sno ,sname ;--移動游標
while
tab_cursor %found
loop
dbms_output.put_line (
'學號:'
||sno ||
'姓名:'
||sname );
fetch tab_cursor into sno ,sname ;
end loop;
close tab_cursor ;
else
dbms_output.put_line (
'沒有找到你想要找的表數據信息'
);
end
if
;
end;
-----------------------------------ref游標題目---------------------------------
SQL > select * from student ;
XH KC
---------- ----------
1
語文
1
數學
1
英語
1
歷史
2
語文
2
數學
2
英語
3
語文
3
英語
9
rows selected
SQL >
完成的任務 :
生成student2表 (xh number, kc varchar2 (
50
));
對應於每一個學生,求出他的總的選課記錄,把每個學生的選課記錄插入到student2表中。
即,student2中的結果如下:
XH KC
--- -------------------------------------------
1
語文數學英語歷史
2
語文數學英語
3
語文英語
create table student2 (xh number, kc varchar2 (
50
));
declare
kcs varchar2 (
50
);
kc varchar2 (
50
);
type ref_cursor is ref cursor; --聲明一個ref游標類型
stu_cursor ref_cursor ;--定義一個ref游標類型的變量
type tab_type is table of number; --聲明一個table類型
tab_xh tab_type ;--定義一個表類型的變量
cursor cursor_xh is select distinct( xh) from student; --聲明一個游標
begin
open cursor_xh; --打開游標
fetch cursor_xh bulk collect into tab_xh; --提取數據到表中
for
i in
1
.. tab_xh.count
loop
kcs :=
''
;
open stu_cursor
for
select kc from student s where s.xh = tab_xh(i ); --打開ref游標
fetch stu_cursor into kc ; --移動游標
while
stu_cursor %found
loop
kcs := kc ||kcs ; --連接字符串使用||而不是+
fetch stu_cursor into kc ; --移動游標
end loop;
insert into student2 (xh , kc ) values( i, kcs);
close stu_cursor ;
end loop;
close cursor_xh ;
end;
|