如何在不丢失该表中的数据的情况下将值插入嵌套表中?

时间:2017-11-07 06:56:54

标签: oracle oracle11g

如何将新数据插入到现有行的嵌套表中?例如,我已经定义了

CREATE OR REPLACE TYPE businessTableForCategories AS TABLE OF VARCHAR(128);
/

CREATE TABLE Category (
name                    VARCHAR(128) PRIMARY KEY,
businesses              businessTableForCategories
) NESTED TABLE businesses STORE AS categoryBusinessTable;

在类别中说,有name = 'Restaurant'businesses = businessTableForCategories('xzqpehc234ajdpa8')的条目。

如何在不删除条目的情况下将新数据插入到Category中该条目的嵌套表中,或者丢失存储在嵌套表中的数据?

我问,因为我尝试插入的一个条目需要一个长度为25137个字符的insert语句,这超出了Oracle对单个命令的限制。这是因为该类别中有许多企业。我想创建类别,然后将业务逐个(或者可能是小组)插入嵌套表" business"。

1 个答案:

答案 0 :(得分:3)

使用MULTISET UNION [ALL|DISTINCT]运算符:

SQL Fiddle

Oracle 11g R2架构设置

CREATE OR REPLACE TYPE businessTableForCategories AS TABLE OF VARCHAR(128);
/

CREATE TABLE Category (
name                    VARCHAR(128) PRIMARY KEY,
businesses              businessTableForCategories
) NESTED TABLE businesses STORE AS categoryBusinessTable
/

INSERT INTO Category VALUES (
  'Restaurant',
  businessTableForCategories('xzqpehc234ajdpa8')
)
/

UPDATE Category
SET businesses = businesses
                 MULTISET UNION ALL 
                 businessTableForCategories('other_value')
WHERE name = 'Restaurant'
/

查询1

SELECT *
FROM   category

<强> Results

|       NAME |                   BUSINESSES |
|------------|------------------------------|
| Restaurant | xzqpehc234ajdpa8,other_value |

查询2

或者使用绑定变量在查询中包含该集合:

DECLARE
  businesses businessTableForCategories := businessTableForCategories();
BEGIN
  businesses.EXTEND( 10000 );
  FOR i IN 1 .. 10000 LOOP
    businesses(i) := DBMS_RANDOM.STRING( 'x', 128 );
  END LOOP;
  INSERT INTO Category VALUES ( 'lots of data', businesses );
END;

查询3

SELECT name, CARDINALITY( businesses )
FROM   Category

<强> Results

|         NAME | CARDINALITY(BUSINESSES) |
|--------------|-------------------------|
| lots of data |                   10000 |
|   Restaurant |                       2 |