从Oracle游标中获取下一行数据

8
我正在构建一个嵌套树,并需要使用Oracle获取游标中下一行的数据。我仍然需要当前行,所以向前循环不是解决方案。例如:
  OPEN emp_cv FOR sql_stmt;
  LOOP
  FETCH emp_cv INTO v_rcod,v_rname,v_level;
  EXIT WHEN emp_cv%NOTFOUND; 
  /*here lies the code for getting v_next_level*/
      if v_next_level > v_level then
          /*code here*/
          elsif v_next_level < v_level then
          /*code here*/
          else
          /*code here*/
          end if;
  END LOOP;
  CLOSE emp_cv;
3个回答

20

使用LEAD和LAG函数

LEAD函数可以计算下一行(即当前行之后的行)的表达式并将该值返回到当前行。LEAD的通用语法如下所示:

LEAD (sql_expr,offset,default) OVER (analytic_clause)

sql_expr是从前导行计算的表达式。

offset是相对于当前行的前导行的索引。offset是一个正整数,默认为1。

default是如果指向分区范围外的行,则返回的值。

LAG的语法类似,只不过它的offset进入到前一行。

SELECT deptno, empno, sal,
LEAD(sal, 1, 0) OVER (PARTITION BY dept ORDER BY sal DESC) NEXT_LOW_SAL,
LAG(sal, 1, 0) OVER (PARTITION BY dept ORDER BY sal DESC) PREV_HIGH_SAL
FROM emp
WHERE deptno IN (10, 20)
ORDER BY deptno, sal DESC;

 DEPTNO  EMPNO   SAL NEXT_LOWER_SAL PREV_HIGHER_SAL
------- ------ ----- -------------- ---------------
     10   7839  5000           2450               0
     10   7782  2450           1300            5000
     10   7934  1300              0            2450
     20   7788  3000           3000               0
     20   7902  3000           2975            3000
     20   7566  2975           1100            3000
     20   7876  1100            800            2975
     20   7369   800              0            1100

8 rows selected.

我正在使用“按名称排序同级节点”功能,但是Oracle报错了。不过感谢你向我展示这样一个很棒的函数。 - Dan Ganiev

3
我是这样做的。我在向后构建一棵树。我必须检查第一次迭代。
OPEN emp_cv FOR sql_stmt; 
 LOOP     
 if emp_cv%notfound then
    /*some code*/
    exit;
 end if;
 FETCH emp_cv INTO v_new_level;      
    if not b_first_time then    
      if v_new_level > v_level then
       /*some code*/
      elsif v_new_level < v_level then              
       /*some code*/
      else
       /*code*/
      end if;
    else    
      b_first_time:=false;
    end if;  
      v_level:=v_new_level;    
  END LOOP;
  CLOSE emp_cv;

2

是否最好存储之前的级别并使用它。类似以下方式:

  /* set to a value lesser than the lowest value possible for level
     am assuming 0 is the lowest value possible */
  v_previous_level := -1; 

  OPEN emp_cv FOR sql_stmt; 
  LOOP 
  FETCH emp_cv INTO v_rcod,v_rname,v_level; 
  EXIT WHEN emp_cv%NOTFOUND;  
      /* you'd probably have to update v_previous_level in one of 
         these conditions (depends on your logic) */
      if v_previous_level > v_level then 
          /*code here*/ 
          elsif v_previous_level < v_level then 
          /*code here*/ 
          else 
          /*code here*/ 
          end if; 
  END LOOP; 
  CLOSE emp_cv; 

实际上,我已经尝试过了,当然它可以工作,但是我有一个特殊的HTML结构,这是jQuery插件所需要的,而采用这种方法树形结构无法正确构建。 - Dan Ganiev

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接