oracle中的for循環用法比較簡單,但是在一次用到包涵select語句的for循環時,還是發現了一些自己以前沒有注意的東西。
Oracle中的for循環用法比較簡單,,但是在一次用到包涵select語句的for循環時,還是發現了一些自己以前沒有注意的東西。
我的代碼如下:
declare
val1 date;
val2 date;
begin
for i in (select empno from emp_s) loop
select hiredate into val1 from (select empno,hiredate,rank()over(order by hiredate) a from emp_s where empno=i) where a=1;
select hiredate into val2 from (select empno,hiredate,rank()over(order by hiredate) a from emp_s where empno=i) where a=2;
dbms_output.put_line(val2-val1);
end loop;
exception
when others then
dbms_output.put_line(sqlerrm);
end;
編譯的時候發現抛出兩處PLS-00382錯誤。修改後編譯通過!(修改處用紅字标明!)
declare
val1 date;
val2 date;
begin
for i in (select empno from emp_s) loop
select hiredate into val1 from (select empno,hiredate,rank()over(order by hiredate) a from emp_s where empno=i.empno) where a=1;
select hiredate into val2 from (select empno,hiredate,rank()over(order by hiredate) a from emp_s where empno=i.empno) where a=2;
dbms_output.put_line(val2-val1);
end loop;
exception
when others then
dbms_output.put_line(sqlerrm);
end;
從上面的兩個例子裡面我們可以很明顯的看出來,在包涵select語句的for循環中,變量i是被當做表類型來處理的(即使你的select語句中隻取了一列資料)。是以當我們把i改成i.empno時編譯順利通過。
![](https://img.laitimes.com/img/__Qf2AjLwojIjJCLyojI0JCLiYWan5ybn9GbvwVZslmZ4Vnbpx2Lc52YuAHaw5yd3d3Lc9CX6MHc0RHaiojIsJye.gif)
本文原創釋出php中文網,轉載請注明出處,感謝您的尊重!