oracle—如何使用pl/sql将获取的大量值存储到单个变量中,并将所有值插入到一个变量中

zpqajqem  于 2021-07-26  发布在  Java
关注(0)|答案(1)|浏览(365)

笔记
有人告诉我如何将单列存储的多行值存储到单个变量中,并代表该变量一次单击就将返回的值存储在表中如何使用pl/sql实现这种场景。
像这样的查询返回一列多行,我想把它存储到一些var中,并在单击过程中插入所有值。它将生成错误的错误图像

DECLARE
    l_respondent_id   VARCHAR(100);
BEGIN
    FOR c IN (
        SELECT
            s.gr_number
        FROM
            student s
            LEFT JOIN class_time ct ON ct.class_id = s.class_id
                                       AND instr(s.class_time, ct.class_time) > 0
        WHERE
            upper(TRIM(ct.class_id)) = upper(TRIM(:app_user))
            AND s.gr_number IS NOT NULL
            AND is_active_flg = 'Y'
    ) LOOP
        l_respondent_id := c.gr_number;
        BEGIN
            SELECT
                s.gr_number
            INTO l_respondent_id
            FROM
                student s
                LEFT JOIN class_time ct ON ct.class_id = s.class_id
                                           AND instr(s.class_time, ct.class_time) > 0
            WHERE
                upper(TRIM(ct.class_id)) = upper(TRIM(:app_user))
                AND s.gr_number IS NOT NULL
                AND is_active_flg = 'Y'
                AND s.gr_number = c.gr_number;

        EXCEPTION
            WHEN no_data_found THEN
                l_respondent_id := NULL;
        END;

        IF l_respondent_id IS NULL THEN
            INSERT INTO student_class_attend ( gr_number ) VALUES ( c.gr_number ) RETURNING gr_number INTO l_respondent_id;

        END IF;

    END LOOP;
END;
uttx8gqw

uttx8gqw1#

为此,您可能可以使用嵌套表、批量收集和forall。简化示例:
表格和数据

create table students( id primary key, fname, lname )
as
select 1, 'fname_1', 'lname_1' from dual union all
select 2, 'fname_2', 'lname_2' from dual union all
select 3, 'fname_3', 'lname_3' from dual union all
select 4, 'fname_4', 'lname_4' from dual union all
select 5, 'fname_5', 'lname_5' from dual union all
select 6, 'fname_6', 'lname_6' from dual ;

-- empty
create table attendance( studentid number references students, when_ date ) ;

匿名块

declare

-- This will allow you to store several studentIDs:
  type studentid_t is table of students.id%type index by pls_integer ;

-- The current attendance list.  Notice the TYPE.  
  attendancelist studentid_t ;

begin

-- Your query (including all the necessary joins and conditions) here.
-- In this case, we will pick up 3 of the 6 IDs.
  select id bulk collect into attendancelist
  from students
  where mod( id, 2 ) = 0 ; 

-- Write a _single_ DML statement after FORALL (which is not a loop - see docs) 
  forall i in attendancelist.first .. attendancelist.last
    insert into attendance( studentid, when_ ) 
      values( attendancelist( i ) , sysdate ) ; -- use whatever you need here

end ;
/

结果(执行匿名块后)

SQL> select * from attendance ;

 STUDENTID WHEN_    
---------- ---------
         2 07-JUN-20
         4 07-JUN-20
         6 07-JUN-20

在这儿摆弄。

相关问题