我使用游标中的信息填充关联数组,现在我想将关联数组信息插入表中。这怎么可能?考虑从记录创建关联数组。
SET SERVEROUTPUT ON
DECLARE
TYPE rec_depts_info IS RECORD(
v_dept_id departments.department_id%TYPE,
v_dept_name departments.department_name%TYPE);
TYPE typ_depts_info IS TABLE OF rec_depts_info
INDEX BY PLS_INTEGER;
CURSOR cur_depts_info_1
IS
SELECT department_id, department_name
FROM departments
WHERE department_id IS NOT NULL
AND department_name IS NOT NULL;
t_depts_info_1 typ_depts_info;
rec_depts_info_1 rec_depts_info;
v_counter_1 PLS_INTEGER := 1;
v_counter_2 PLS_INTEGER := 1;
BEGIN
v_counter_1 := v_counter_1 + 1;
FOR depts_info IN cur_depts_info_1
LOOP
t_depts_info_1(v_counter_1).v_dept_id := depts_info.department_id;
t_depts_info_1(v_counter_1).v_dept_name := depts_info.department_name;
EXIT WHEN cur_depts_info_1%NOTFOUND;
END LOOP;
LOOP
INSERT INTO tabla_pruebas
VALUES(t_depts_info_1(v_counter_2).v_dept_id,
t_depts_info_1(v_counter_2).v_dept_name)
RETURNING column_1, column_2
INTO rec_depts_info_1.v_dept_id, rec_depts_info_1.v_dept_name;
DBMS_OUTPUT.PUT_LINE('DEPT ID: ' || rec_depts_info_1(v_counter_2).v_dept_id
|| ' DEPT NAME: ' ||
rec_depts_info_1(v_counter_2).v_dept_name);
v_counter_2 := v_counter_2 + 1;
EXIT WHEN SQL%NOTFOUND;
END LOOP;
END;
我正在尝试使用简单的LOOP将数据插入新的tabla但我收到以下错误:
Informe de error -
ORA-06550: line 51, column 41:
PLS-00222: no function with name 'REC_DEPTS_INFO_1' exists in this scope
ORA-06550: line 51, column 5:
PL/SQL: Statement ignored
06550. 00000 - "line %s, column %s:\n%s"
*Cause: Usually a PL/SQL compilation error.
*Action:
感谢!!!
答案 0 :(得分:3)
您可以使用 the FORALL
bulk syntax一次插入所有数组值,而不是显式循环:
FORALL i IN t_depts_info_1.first..t_depts_info_1.last
INSERT INTO tabla_pruebas
VALUES(t_depts_info_1(i).v_dept_id,
t_depts_info_1(i).v_dept_name);
Read more关于FORALL
以及其他批量查询和绑定主题。使用BULK COLLECT
填充数组,您可以将代码简化为:
DECLARE
TYPE rec_depts_info IS RECORD(
v_dept_id departments.department_id%TYPE,
v_dept_name departments.department_name%TYPE);
TYPE typ_depts_info IS TABLE OF rec_depts_info
INDEX BY PLS_INTEGER;
t_depts_info_1 typ_depts_info;
BEGIN
SELECT department_id, department_name
BULK COLLECT INTO t_depts_info_1
FROM departments
WHERE department_id IS NOT NULL
AND department_name IS NOT NULL;
FORALL i IN t_depts_info_1.first..t_depts_info_1.last
INSERT INTO tabla_pruebas
VALUES(t_depts_info_1(i).v_dept_id,
t_depts_info_1(i).v_dept_name);
END;
/
虽然有了这个人为的例子,你根本不需要集合或任何PL / SQL,你可以做一个简单的insert...select
:
INSERT INTO tabla_pruebas (column_1, column_2)
SELECT department_id, department_name
FROM departments
WHERE department_id IS NOT NULL
AND department_name IS NOT NULL;