---
title: "Oracle中的loop循环的例子"
author: "danielhjd"
date: "2011-05-25T15:07:24Z"
tags: ["Oracle"]
categories: ["数据库"]
slug: "oracle-loop"
draft: false
lastmod: "2011-05-25T15:07:24Z"
id: 1058246
url: "https://danielhjd.iteye.com/blog/1058246"
---

**第一：loop... exit when...end loop;**

```
declare
temp_salary employee.salary%type;
temp_emp employee%rowtype;
cursor mycursor is 
select * from employee where employee.salary>temp_salary;
begin
temp_salary:=2000;
open mycursor;
loop 
fetch mycursor into temp_emp;
exit when mycursor%notfound;
dbms_output.put_line('编号：'||temp_emp.empid||','||'名字:'||temp_emp.empname||','||'薪水:'||temp_emp.salary);
end loop;
end;
```

 output:

```
编号：13,名字:aaa,薪水:2440
编号：10,名字:dwj,薪水:2140
编号：12,名字:eee,薪水:2140
```

 

loop

statament1;

exit when condition;

statament2;

end loop;

 

**第二：for i in 1...n loop...end loop;**

```
declare
temp_emp employee%rowtype;
cursor cur2 is select * from employee where employee.salary>2000;
begin
if cur2%isopen = false then
open cur2;
end if;
for i in 0..3 loop
fetch cur2 into temp_emp;
exit when cur2%notfound;
dbms_output.put_line('编号：'||temp_emp.empid||','||'名字:'||temp_emp.empname||','||'薪水:'||temp_emp.salary);
end loop;

close cur2;
end;
```

 output:

```
编号：13,名字:aaa,薪水:2440
编号：10,名字:dwj,薪水:2140
编号：12,名字:eee,薪水:2140
```

 

for i in 0...n loop

statement1;

exit when condition;

statament;

end loop;

 

备注：此例子的代表性不强...不过可以初步了解loop的功能。