7

ネストされたツリーを構築しています。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;
4

3 に答える 3

19

LEAD 関数と LAG 関数を使用する

LEAD には、次の行 (現在の行の後に来る行) で式を計算し、現在の行に値を返す機能があります。LEAD の一般的な構文を以下に示します。

LEAD (sql_expr、オフセット、デフォルト) OVER (analytic_clause)

sql_exprは、先行行から計算する式です。

オフセットは、現在の行を基準とした先行行のインデックスです。オフセットは正の整数で、デフォルトは 1 です。

defaultは、 がパーティション範囲外の行を指している場合に返す値です。

LAG の構文は、LAG のオフセットが前の行に入ることを除いて似ています。

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.
于 2010-06-15T07:26:52.620 に答える
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;
于 2010-06-16T08:24:34.403 に答える
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; 
于 2010-06-15T07:10:22.697 に答える