Oracle中循环语句的几种用法

oracle中的循环语句大致分三种:Loop、While、For

1.Loop

declare i number;
begin
  i := 0;
  LOOP
    Exit When(i > 5);
    Dbms_Output.put_line(i);
    i := i + 1;
  END LOOP;
end;

等价于

declare i number;
begin
  i := 0;
  loop
    if i > 5 then
      exit;
    end if;
    dbms_output.put_line(i);
    i := i + 1;
  end loop;
end;

执行结果:

0
1
2
3
4
5


2.While

declare i number;
begin
  i := 0;
  while i < 5 loop
    i := i + 1;
    dbms_output.put_line(i);
  end loop;
end;

执行结果:

1
2
3
4
5
 

3.For

for循环有两种,普通for循环和游标for循环:

普通for循环实例

declare i number;
begin
  i:=0;
  for i in 1..5 loop
  dbms_output.put_line(i);
  end loop;
end;

 执行结果:

1
2
3
4
5
 

游标for循环实例:


declare userRow emp%rowtype;
  cursor userRows is select * from emp;
begin
  for userRow in userRows
  loop
    dbms_output.put_line('员工姓名:'|| userRow.ENAME);
  end loop;
end;


执行结果:

员工姓名:SMITH
员工姓名:ALLEN
员工姓名:WARD
员工姓名:JONES
员工姓名:MARTIN
员工姓名:BLAKE
员工姓名:CLARK
员工姓名:SCOTT
员工姓名:KING
员工姓名:TURNER
员工姓名:ADAMS
员工姓名:JAMES
员工姓名:FORD
员工姓名:MILLER
 

发布了163 篇原创文章 · 获赞 46 · 访问量 17万+

猜你喜欢

转载自blog.csdn.net/liangmengbk/article/details/101200232