从oracle pl sql中的游标错误中获取变量

时间:2014-04-11 13:04:50

标签: oracle plsql

我使用游标获取值:

CURSOR Colcond
   IS
      SELECT   CONDITION
        FROM   CONDITION_TAB
       WHERE   PROCEDURE_NAME = 'CALL_VOL';

在第一次迭代中,它将获取" SUM(CASE WHEN CALL_REF = 0 THEN 1 ELSE 0 END)"。

在我的计划中:

OPEN Colcond;

FETCH Colcond INTO cond_val;

    SELECT  Appnum, customer_num,'"cond_val"'
    INTO   iappnum, icustnum,icond_val
    FROM   CALL_DETAILS WHERE APPNUM = val_appl
    AND customer_num = val_cust
    Group by APPLICATION_NUM,CUST_SGMT_NUM,DNIS;

INSERT INTO S_CALL_VOLUME VALUES   (iappnum, icustnum, SYSDATE, icond_val);

记录变量" icond_val" insert是SUM(CASE WHEN CALL_REF=0 THEN 1 ELSE 0 END)而不是值(10或20或50)。

如何获取值而不是Sum case语句?

1 个答案:

答案 0 :(得分:1)

您需要使用动态SQL将您从condition_tab表中选择的值合并到下一个查询中。这是一个匿名块而不是过程的示例:

declare
  val_appl number; -- procedure argument in your version?
  val_cust number; -- procedure argument in your version?

  query_string varchar2(2000);
  cond_val condition_tab.condition%type;
  iappnum call_details.appnum%type;
  icustnum call_details.customer_num%type;
  icond_val number;
  cursordyn sys_refcursor;
  cursor colcond is
    select condition
    from condition_tab
    where procedure_name = 'CALL_VOL';

begin
  open colcond;
  fetch colcond into cond_val;
  close colcond;

  query_string:='select appnum, customer_num, ' || cond_val || ' from call_details '
    || 'where appnum = :val_appl and customer_num = :val_cust '
    || 'group by application_num,cust_sgmt_num,dnis';

  open cursordyn for query_string using val_appl, val_cust;
  fetch cursordyn into iappnum, icustnum, icond_val;
  close cursordyn;

  insert into s_call_volume values (iappnum, icustnum, sysdate, icond_val);
end;
/

您的列名似乎有些不一致,因此可能需要进行一些调整。

对于两个游标,您只选择一行,因此(a)它们实际上不需要是游标,它们只能是select into语句; (b)第二个是从where子句中选择两列似乎有点无意义 - 当你在插入中使用iappnum时,你可以只使用val_app等。所以我认为你可以将其简化为:

declare
  val_appl number; -- procedure argument in your version?
  val_cust number; -- procedure argument in your version?

  query_string varchar2(2000);
  cond_val condition_tab.condition%type;
  icond_val number;
begin
  select condition
  into cond_val
  from condition_tab
  where procedure_name = 'CALL_VOL';

  query_string:='select ' || cond_val || ' from call_details '
    || 'where appnum = :val_appl and customer_num = :val_cust '
    || 'group by application_num,cust_sgmt_num,dnis';

  execute immediate query_string into icond_val using val_appl, val_cust;

  insert into s_call_volume values (val_appl, val_cust, sysdate, icond_val);
end;
/

如果任一查询没有返回一行,则会出错。如果condition_tab查询没有找到数据,您的游标版本将会出错,如果有多个数据,则仅使用一个'条件';如果有倍数,则仅使用第二个查询的第一个结果。如果你期望任何一个的倍数(不确定你的实际分组应该是什么,它看起来也不一致)那么你需要循环遍历光标,重复获取。

希望这会让你开始。