从SELECT语句中将表插入具有VARRAY类型数据类型的表中

时间:2020-11-05 08:15:02

标签: oracle plsql

创建的类型emp_varray_typ如下:

CREATE TYPE emp_varray_typ AS VARRAY(50) OF VARCHAR2(25);

表DEPT_ARRAY创建为 创建表部(DEPT_NO NUMBER,EMP_NM_ARRAY emp_varray_typ);

EMPLOYEE表如下:

**DEPT_NO | EMP_NM**
  10      | Scot
  10      | Tiger
  10      | John
  20      | Cindy
  20      | Rock

想要将EMPLOYEE表中的数据作为2条记录(DEPT_ARRAY作为数组插入EMP_NM中)插入EMP_NM_ARRAY表中,例如

**DEPT_NO | EMP_NM_ARRAY**
10      | {Scot, Tiger, John}
20      | {Cindy, Rock}

是否可以使用SQL语句插入?

1 个答案:

答案 0 :(得分:2)

您可以使用collect聚合函数并将其强制转换为amp_varray_typ

create type emp_varray_typ as varray(50) of varchar2(25);

create table dept (dept_no number, emp_nm_array emp_varray_typ);

create table employee (dept_no, emp_nm) as
select 10, 'Scot' from dual union all
select 10, 'Tiger' from dual union all
select 10, 'John' from dual union all
select 20, 'Cindy' from dual union all
select 20, 'Rock' from dual;
insert into dept (dept_no, emp_nm_array)
select dept_no, cast(collect(emp_nm) as emp_varray_typ)
from   employee
group by dept_no;

更多背景:www.oracle-developer.net/display.php?id=306