将行插入到对象的Oracle类型表中

时间:2018-04-11 23:10:18

标签: oracle collections types oracle11g

我能够将查询BULK收集到类型为object的表中,但看起来似乎不行 做一个简单的插入。我是否必须在单行插入时使用BULK收集?

DROP TYPE T_TABLE;
/

CREATE OR REPLACE TYPE T_ROW AS OBJECT   
  (
    ID NUMBER(10),
    DESCRIPTION VARCHAR2(50)
  );
/ 

CREATE OR REPLACE TYPE T_TABLE AS TABLE OF T_ROW;
/

DECLARE

V_TABLE T_TABLE;
V_ROW T_ROW;

BEGIN
  INSERT INTO TABLE(V_TABLE) VALUES (1,'XXX');
  --INSERT INTO T_TABLE(V_TABLE) VALUES (T_ROW(1,'XXX'));
  --INSERT INTO TABLE(V_TABLE) VALUES (V_ROW(1,'XXX'));
END;

1 个答案:

答案 0 :(得分:3)

有多种方法可以将项目添加到集合中,包括:

在构造函数中填充集合:

DECLARE
  V_TABLE T_TABLE := T_TABLE(
    T_ROW( 1, 'XXX' ),
    T_ROW( 2, 'YYY' ),
    T_ROW( 3, 'ZZZ' )
  );
BEGIN
  -- Do stuff with the collection here...
  NULL;
END;
/

或者,逐行填充表格:

DECLARE
  V_TABLE T_TABLE;
BEGIN
  -- Constructor
  V_TABLE := T_TABLE();
  -- Extend by the default, 1 element
  V_TABLE.EXTEND;
  -- Populate that element
  V_TABLE(1) := T_ROW( 1, 'XXX' );

  -- Extend by 2 elements
  V_TABLE.EXTEND(2);
  V_TABLE(2) := T_ROW( 2, 'YYY' );
  V_TABLE(V_TABLE.COUNT) := T_ROW( 3, 'ZZZ' );

  -- Do stuff with the collection here...
END;
/

或者,使用SQL和BULK COLLECT INTO

DECLARE
  V_TABLE T_TABLE;
BEGIN
  SELECT rw
  BULK COLLECT INTO V_TABLE
  FROM   (
    SELECT T_ROW( 1, 'XXX' ) AS rw FROM DUAL UNION ALL
    SELECT T_ROW( 2, 'YYY' ) FROM DUAL UNION ALL
    SELECT T_ROW( 3, 'ZZZ' ) FROM DUAL
  );
END;
/

使用MULTISET UNION ALL来连接集合:

DECLARE
  V_TABLE1 T_TABLE := T_TABLE( T_ROW( 1, 'XXX' ), T_ROW( 2, 'YYY' ) );
  V_TABLE2 T_TABLE := T_TABLE( T_ROW( 3, 'ZZZ' ) );
  V_TABLE3 T_TABLE;
BEGIN
  V_TABLE3 := V_TABLE1 MULTISET UNION ALL V_TABLE2;
END;
/

或者,如果集合是嵌套表,则可以在SQL中执行:

SQL Fiddle

Oracle 11g R2架构设置

CREATE TABLE test(
  id NUMBER,
  tbl T_TABLE
) NESTED TABLE tbl STORE AS test_tab
/

INSERT INTO test VALUES ( 1, T_TABLE() )
/
INSERT INTO TABLE( SELECT tbl FROM test WHERE id = 1 ) VALUES ( T_ROW( 1, 'XXX' ) )
/
INSERT INTO TABLE( SELECT tbl FROM test WHERE id = 1 ) VALUES ( T_ROW( 2, 'YYY' ) )
/

查询1

SELECT t.id, tt.id, tt.description
FROM   test t
       CROSS JOIN
       TABLE( t.tbl ) tt

<强> Results

| ID | ID | DESCRIPTION |
|----|----|-------------|
|  1 |  1 |         XXX |
|  1 |  2 |         YYY |