选择into语句为null或多个值

时间:2018-05-07 05:27:47

标签: function plsql select-into

我陷入了plsql,因为我已经制作了一个函数,如果只有值选择进入,我必须更新表格。

如果没有,那么不是,如果有多个,则必须更新并删除所有值。

在下面的函数中,如果在第一次选择进入空值时,那么不应该转到异常处理应该只更新CUSTOMER表并且只从表3中删除,如果有一个或多个值,则对每个值进行全部更新和删除

 create or replace FUNCTION  FUNCTION_NAME (
   from_PARTICIPANT_KEY1   IN NUMBER
)
  RETURN 
IS
   to_participant_key1   NUMBER (11);
BEGIN
   SELECT   to_participant_key
     INTO   to_participant_key1
     FROM   TABLE2
    WHERE   FROM_PARTICIPANT_KEY = from_PARTICIPANT_KEY1;




  UPDATE   CUSTOMERS C
      SET   C.CUSTOMER_STATUS_CD =
               NVL (
                  (SELECT   old_status_cd
                     FROM   TABLE1
                    WHERE   PARTICIPANT_UID = from_PARTICIPANT_KEY1
                            AND participant_cd = 'CUSTOMER'),
                  C.CUSTOMER_STATUS_CD
               )
    WHERE   C.CUSTOMER_UID = from_PARTICIPANT_KEY1;



   UPDATE   subscribers C
      SET   C.STATUS_CD =
               NVL (
                  (SELECT   old_status_cd
                     FROM   TABLE1
                    WHERE   PARTICIPANT_UID = to_participant_key1
                            AND participant_cd = 'SUBSCRIBER'),
                  C.STATUS_CD
               )
    WHERE   C.account_no = to_participant_key1;

   DBMS_OUTPUT.PUT_LINE ('Delete TABLE1 rows');

   DELETE FROM   TABLE3
         WHERE   PARTICIPANT_UID = from_PARTICIPANT_KEY1 AND participant_cd = 'CUSTOMER';

   DELETE FROM   TABLE1
         WHERE   PARTICIPANT_UID = to_PARTICIPANT_KEY1 AND participant_cd = 'SUBSCRIBER';



   COMMIT;



EXCEPTION  -- exception handlers begin
   WHEN NO_DATA_FOUND  THEN  -- handles 'division by zero' error
      dbms_output.put_line('Customer not found ' || from_PARTICIPANT_KEY1);

   WHEN OTHERS THEN  -- handles all other errors
      dbms_output.put_line('Some other kind of error occurred.');


END;

1 个答案:

答案 0 :(得分:0)

您可以使用BULK COLLECT INTO并迭代收集。

首先,您必须声明(或使用一些现有的)集合类型并创建此类型的变量:

  TYPE participant_keys is table of number (11); 
  l_participant_keys participant_keys;

然后,您的查询将更改为:

  SELECT to_participant_key
  BULK COLLECT INTO to_participant_key1
  FROM TABLE2
  WHERE FROM_PARTICIPANT_KEY = from_PARTICIPANT_KEY1;

如果查询不会返回任何记录,那么您可以使用COUNT

进行检查
if l_participant_keys.COUNT = 0 then
 -- update only CUSTOMER table and only delete from table 3
else
  FOR I IN l_participant_keys.FIRST .. l_participant_keys.LAST LOOP
    --use l_participant_keys(i) do all update and delete for each value
  END LOOP;
end if;