【问题标题】:Inserting INTO a Table with VARRAY Type data type column from a SELECT statement从 SELECT 语句中插入具有 VARRAY 类型数据类型列的表
【发布时间】:2020-11-05 08:15:02
【问题描述】:

TYPE emp_varray_typ 创建如下:

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

表 DEPT_ARRAY 创建为 CREATE TABLE 部门(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语句插入的方法?

【问题讨论】:

    标签: oracle plsql


    【解决方案1】:

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

    【讨论】:

    • 现在我们已经设法将 DEPTNO 的多个值“收集”到单个列中。是否可以使用 SQL 语句对这些列进行比较?示例:Deptno 10 的 emp_nm_array 的值为 {Scot, Tiger, John} Deptno 20 的 emp_nm_array 的值为 {Scot,Tiger} 我们需要确定 Deptno 20 的 emp_nm_array 是否存在于 Deptno 10 的 emp_nm_array 中。
    • 这应该适用于嵌套表集合类型 (type x is table of y) 和子多重集表达式。可变数组不支持这个。
    • 只是补充一下,这是一个有趣的建议。它可以作为经典问题的优雅解决方案客户购买了每件产品,又名Relational Division
    猜你喜欢
    • 2015-10-20
    • 2021-07-16
    • 2019-07-30
    • 1970-01-01
    • 2013-12-25
    • 1970-01-01
    • 1970-01-01
    • 2022-11-20
    • 1970-01-01
    相关资源
    最近更新 更多