How to insert a value into a nested table without losing data in that table?

后端 未结 1 1057
心在旅途
心在旅途 2020-12-20 05:21

How can I insert new data into an existing row\'s nested table? For example, I have defined

CREATE OR REPLACE TYPE businessTableForCategories AS TABLE OF VA         


        
相关标签:
1条回答
  • 2020-12-20 05:36

    Use the MULTISET UNION [ALL|DISTINCT] operator:

    SQL Fiddle

    Oracle 11g R2 Schema Setup:

    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'
    /
    

    Query 1:

    SELECT *
    FROM   category
    

    Results:

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

    Query 2:

    Or use a bind variable to include the collection in the query:

    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;
    

    Query 3:

    SELECT name, CARDINALITY( businesses )
    FROM   Category
    

    Results:

    |         NAME | CARDINALITY(BUSINESSES) |
    |--------------|-------------------------|
    | lots of data |                   10000 |
    |   Restaurant |                       2 |
    
    0 讨论(0)
提交回复
热议问题