从PL / SQL关联数组中的元素中获取不同的值

时间:2017-07-12 20:28:40

标签: sql arrays oracle plsql

假设我的表格XX_TABLE_SAMPLE包含以下记录:

TAB_ID  BATCH_NAME  EMP_NO  EMP_NAME    STATUS      SALARY  CATEGORY
------  ----------  ------  --------    --------    ------- ------------
1       BATCH_A     1       Jared       Active      1000    (NULL)
2       BATCH_A     2       Siege       Active      3000    (NULL)
3       BATCH_A     45      James       Suspended   2000    (NULL)
4       BATCH_B     67      Harry       Active      100     (NULL)
5       BATCH_B     99      Pikachu     Active      10000   (NULL)
6       BATCH_x     100     Eren        Suspended   4000    (NULL)

我有如下的PL / SQL块(请注意评论):

declare

    cursor emp_cur is
    select  *
    from    XX_TABLE_SAMPLE
    where   status = 'Active';

    type emp_cur_type is table of XX_TABLE_SAMPLE%rowtype index by pls_integer;
    emp_rec emp_cur_type;

begin

    open    emp_cur;
    fetch   emp_cur
    bulk collect
    into    emp_rec;
    close   emp_cur;

    /*  do some pre-processing here via another stored procedure
        but the problem is, it has a parameter of p_batch_name, not a type of associative array

        for i in emp_rec.first..emp_rec.last loop
            pay_pkg.validate_pay (p_batch_name => emp_rec(i).p_batch_name);
        end;    
        -- the problem with this is that it will loop 4 times (twice each for BATCH_A and BATCH_B)
           when it should only get the 2 batch names (BATCH_A and BATCH_B)        
    */

    -- then check the salary of the emp and update the associative array    
    for i in emp_rec.first..emp_rec.last loop

        if emp_rec(i).salary > 200 and emp_rec(i).salary < 3000 then

            emp_rec(i).CATEGORY = 'Manager';

        end if;

    end loop;    

    forall i in emp_rec.first..emp_rec.last 
    update  XX_TABLE_SAMPLE
    set     CATEGORY = emp_rec(i).CATEGORY 
    where   TAB_ID   = emp_rec(i).TAB_ID;

end;

有了这个,我想在关联数组中获得元素Batch_Name的不同值 然后将其传递给存储过程pay_pkg.validate_pay

关于如何在不声明另一个显式光标的情况下实现这一点的任何想法?

3 个答案:

答案 0 :(得分:1)

也许是你没有说的其他内容,但如果你需要{"BATCH_A", "BATCH_B"}

为什么不使用:

SELECT DISTINCT BATCH_NAME  
FROM XX_TABLE_SAMPLE 
WHERE status = 'Active'
  AND salary > 200 
  AND salary < 3000

答案 1 :(得分:1)

对我而言,您似乎正在考虑不必要的复杂解决方案。我认为您的示例可以简化为以下解决方案,该解决方案需要零PL / SQL数据结构(r是一种隐式记录类型,但编译器可以为您提供!)。

顺便说一句,PL / SQL中没有必要害怕游标。

declare
  -- a dummy placeholder for the "tricky" subprogram
  procedure validate_pay(p_batch_name in varchar2) is begin null; end;
begin
  for r in (select distinct batch_name
              from xx_sample_data
             where status = 'Active')
  loop
    validate_pay(p_batch_name => r.batch_name);
  end loop;

  update xx_sample_data set
   category = 'Manager'
  where status = 'Active'
    and salary between 201 and 2999
  ;
end;
/

答案 2 :(得分:0)

如果你在oracle 12上,还有另一种方式。

但它涉及从关联数组中选择

Select from PLSQL Associative array?