首页 > 解决方案 > 从 SELECT 语句中插入具有 VARRAY 类型数据类型列的表

问题描述

TYPEemp_varray_typ创建如下:

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

表 DEPT_ARRAY 创建为 CREATE TABLE dept (DEPT_NO NUMBER, EMP_NM_ARRAY emp_varray_typ);

员工表如下:

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

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

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

有没有办法使用 SQL 语句插入?

标签: oracleplsql

解决方案


您可以使用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


推荐阅读