遊標是從表中檢索出結果集,從中每次指向一條記錄進行交互的機制。數據庫
做用編程
指定結果集中特定行的位置。
基於當前的結果集位置檢索一行或連續的幾行。
在結果集的當前位置修改行中的數據。
對其餘用戶所作的數據更改定義不一樣的敏感性級別。
能夠以編程的方式訪問數據庫。
一個簡單實用:
oracle
1
2
3
4
5
6
7
8
9
10
11
12
13
Declare
-- 聲明遊標
Cursor Mycur Is
Select * From Emp;
Empinfo Emp%Rowtype;
Cou Number;
Begin
-- 遊標操做使用循環,可是在操做以前必須先將遊標打開
For Empinfo In Mycur Loop
Cou := Mycur%Rowcount;
Dbms_Output.Put_Line('行號:' || Cou || ' 僱員編號:' || Empinfo.Empno || ' 僱員姓名:' || Empinfo.Ename);
End Loop;
End;
循環取出數據的兩種寫法:
ide
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
Declare
-- 聲明遊標
Cursor Mycur Is
Select * From Emp; -- List (EmpPo)
Empinfo Emp%Rowtype;
Cou Number;
Begin
-- 遊標操做使用循環,可是在操做以前必須先將遊標打開
If Mycur%Isopen Then
Null;
Else
Open Mycur;
End If;
-- 使遊標向下一行
Fetch Mycur
Into Empinfo;
-- 判斷此行是否有數據被發現
While (Mycur%Found) Loop
Cou := Mycur%Rowcount;
Dbms_Output.Put_Line('行號:' || Cou || ' 僱員編號:' || Empinfo.Empno || ' 僱員姓名:' || Empinfo.Ename);
-- 修改遊標,繼續向下
Fetch Mycur
Into Empinfo;
End Loop;
End;
第二種寫法:
oop
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
Declare
-- 聲明遊標
Cursor Mycur Is
Select * From Emp;
Empinfo Emp%Rowtype;
Cou Number;
Begin
-- 遊標操做使用循環,可是在操做以前必須先將遊標打開
If Mycur%Isopen Then
Null;
Else
Open Mycur;
End If;
Loop
-- 使遊標向下一行
Fetch Mycur
Into Empinfo;
Exit When Mycur%Notfound;
Cou := Mycur%Rowcount;
Dbms_Output.Put_Line('行號:' || Cou || ' 僱員編號:' || Empinfo.Empno || ' 僱員姓名:' || Empinfo.Ename);
End Loop;
End;
在存儲過程當中使用遊標
測試
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
Create Or Replace Procedure Myproc(Oi_Return Out Integer) Is
Cursor Mycur Is
Select * From Emp_0915;
Empinfo Emp_0915%Rowtype;
Cou Number;
Exc_Return Exception; -- 程序中間返回自定義異常
Begin
If Mycur%Isopen Then
Null;
Else
Open Mycur;
End If;
Loop
Fetch Mycur
Into Empinfo;
Exit When Mycur%Notfound;
Cou := Mycur%Rowcount;
Dbms_Output.Put_Line(Cou || '開始更新...');
Update Emp_0915 t Set t.Sal = t.Sal + 1 Where t.Empno = Empinfo.Empno;
Dbms_Output.Put_Line(Cou || '更新結束...');
End Loop;
Commit;
Oi_Return := 1;
Exception
When Exc_Return Then
Rollback;
Oi_Return := 0;
End;
在oracle中測試:
it
1
2
3
4
5
6
7
8
9
10
Declare
Re Integer;
Begin
Myproc(Re);
If Re = 1 Then
Dbms_Output.Put_Line(Re || ':執行結束。。。');
Else
Dbms_Output.Put_Line(Re || ':執行錯誤___');
End If;
End;
io