oracle存储过程循环怎么写

oracle存储过程循环怎么写,第1张

Oracle中有三种循环(For、While、Loop):

1、loop循环:

create or replace procedure pro_test_loop is

i number

begin

i:=0

loop

 i:=i+1

 dbms_output.put_line(i)

 if i>5 then

   exit

 end if

end loop

end pro_test_loop

2、while循环:

create or replace procedure pro_test_loop  is

i number

begin

i:=0

while i<5 loop

i:=i+1

dbms_output.put_line(i)

end loop

end pro_test_loop

3、for循环1:

create or replace procedure pro_test_for is

i number

begin

i:=0

for i in 1..5 loop

 dbms_output.put_line(i)

end loop

end pro_test_for

4、for循环2:

create or replace procedure pro_test_cursor is

userRow t_user%rowtype

cursor userRows is

select * from t_user

begin

for userRow in userRows loop

   dbms_output.put_line(userRow.Id||','||userRow.Name||','||userRows%rowcount)

end loop

end pro_test_cursor

首先编写存储过程的整体结构,如下:

create or replace procedure test_proc is

v_date date--变量定义

begin

select sysdate into v_date from dual

end test_proc

2

定义游标

create or replace procedure test_proc is

v_date date--定义变量

cursor cur is select * from ldcode--定义游标

begin

select sysdate into v_date from dual

end test_proc

3

编写for循环:

create or replace procedure test_proc is

v_date date--定义变量

cursor cur is select * from ldcode where rownum<10--定义游标

begin

select sysdate into v_date from dual

--游标for循环开始

for temp in cur loop --temp为临时变量名,自己任意起

Dbms_Output.put_line(temp.Code)--输出某个字段,使用"变量名.列名"即可。

end loop

--游标for循环结束

end test_proc

4

测试运行,点击【DBMS Output】标签页查看结果如下图:

END

二、带参数的游标for循环

1

定义带参数的游标:

cursor cur(v_codetype ldcode.Codetype%TYPE) is

select * from ldcode where codetype = v_codetype--定义游标

定义游标格式:

cursor 游标名称(变量定义) is 查询语句

注意:

where条件中的变量名v_codetype要与游标定义cur(v_codetype ldcode.Codetype%TYPE)中的一致。

2

编写for循环部分:

--游标for循环开始

for temp in cur('llmedfeetype') loop

--temp为临时变量名,自己任意起

--cur('llmedfeetype')为"游标名称(传入的变量)"

Dbms_Output.put_line(temp.Code)--输出某个字段,使用"变量名.列名"即可。

end loop

--游标for循环结束

3

测试运行,点击【DBMS Output】标签页查看结果如下图:

这样使用的:

for

xx

in

(select

语句)

这是隐式游标,这个结构中不能带参数,或者说普通的游标,隐式或显式的都不能带参数,使用参数游标或引用(动态)游标。

例如:

declare

cursor cur(C_value number) is select col_A,col_B from tableA where col_C=C_value

begin

for xx in cur loop

--处理

end loop

end

扩展资料:

注意事项

使用for循环实现

declare

cursor

cur

is

select

*

from

tablename

aw_row

tablename%rowtype

begin

for

raw_row

in

cur

loop

dbms_output.put_line('test')

end

loop

end

for语句直接帮做了游标的打开关闭,以及判断工作,所以比较常用。


欢迎分享,转载请注明来源:内存溢出

原文地址: https://outofmemory.cn/sjk/6908784.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2023-03-30
下一篇 2023-03-30

发表评论

登录后才能评论

评论列表(0条)

保存