且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

将多列减号查询的结果存储在 Oracle PL/SQL 中的变量中

更新时间:2022-12-03 18:51:00

SYS.ODCINUMBERLIST 只是一个列表,其中每条记录都有一个编号.您需要使用新的记录类型来存储每行中的多个字段.

SYS.ODCINUMBERLIST is just a list where each record has a single number. You need to use a new record type to store the multiple fields in each row.

您可以定义一个记录类型来代替 SYS.ODCINUMBERLIST.但我倾向于将 SELECT 语句移动为显式游标,以便您可以将新类型定义为游标 %ROWTYPE.这样,您的记录类型和选择语句始终保持一致,但它会稍微改变您的代码结构.

You could define a record type to use in place of SYS.ODCINUMBERLIST. But I'd be inclined to move the SELECT statement to be an explicit cursor, so that you could define a new type as cursor %ROWTYPE. That way, your record type and the select statement are always consistent, but it changes the structure of your code a bit.

这是这种方法:

DECLARE 

  CURSOR c_select IS
      SELECT project_id, project_name
      FROM 
        (
          SELECT t1.project_id, t1.project_name FROM table_one t1
          MINUS
          SELECT t2.project_id, t2.project_name FROM table_two t2 );

  TYPE l_missing_row_list_typ IS TABLE OF c_select%ROWTYPE;
  l_missing_row_list l_missing_row_list_typ;
  
BEGIN
  OPEN c_select;
  FETCH c_select BULK COLLECT INTO l_missing_row_list;
  CLOSE c_select;
  
  FORALL i IN l_missing_row_list.FIRST..l_missing_row_list.LAST
    INSERT INTO table_two VALUES ( l_missing_row_list(i).project_id, l_missing_row_list(i).project_name );
    
  COMMIT;
  
  -- Values are now inserted and you have the list of IDs in l_missing_row_list to add to your email.
END;

关于BULK COLLECT 的一个说明(此处和您的原始帖子中都有)——您批量收集的数据存储在 PGA 内存中.所以不要使用这个代码,如果有变化,新记录的数量会不合理(可能超过几千).

One note about the BULK COLLECT (both here and in your original post) -- the data you are bulk collecting is stored in PGA memory. So do not use this code as is if there is a change the number of new records will be unreasonable (maybe more than a few thousand).