首页 文章

PL / SQL - 声明一个保存表和操作记录的记录?

提问于
浏览
0

我目前正试图找出一个关于我的任务的问题 . 我之前从未使用过数组,但我已经完成了集合,触发器,函数,过程和游标 . 我不是要求答案,而是对此有所帮助,因为我对如何处理它感到困惑 .

  • 声明记录LOCATIONS表(LOCATION_ID,STREET_ADDRESS,POSTAL_CODE,CITY,STATE_PROVINCE和COUNTRY_ID)和操作的记录 .

  • 声明一个数组,其中将位置记录保存为元素 .

  • 通过填充要处理的每个位置的值来初始化数组

  • 操作类型可以是“U”表示更新,“I”表示插入,“D”表示删除

  • 从头到尾迭代所有数组元素,并对数组中定义的每个位置执行以下逻辑:

  • 如果操作类型为“U”,则使用来自数组的值更新LOCATIONS表 . 如果在表上找不到位置标识,请将其作为新记录插入 .

  • 如果操作类型为“I”,则将记录插入表中 . 值应来自数组

  • 如果操作类型为“D”,则从表中删除该位置 .

  • 对于每个操作,在完成该过程后显示一条消息

  • 如果操作员类型与U,I,D不同,则显示正确的消息,指示'Invalid operation' .

  • 提交所有交易

关于操作的部分也让我困惑,因为我做了一些工作,你会在触发器中使用运算符,但它不涉及数组:

BEGIN
IF INSERTING THEN
    INSERT INTO carlog
    VALUES ('INSERT',user, SYSDATE, UPPER(:NEW.serial), UPPER(:NEW.make),
        UPPER(:NEW.model), UPPER(:NEW.color));
END IF;
IF UPDATING THEN
    INSERT INTO carlog
    VALUES ('UPDATE',user, SYSDATE,:old.serial, old.make, 
        old.model, old.color);
END IF;
IF DELETING THEN
    INSERT INTO carlog
    VALUES ('DELETE',user, SYSDATE,:old.serial, old.make, 
        old.model, old.color);
END IF;
END;

1 回答

  • 1

    数组只是一种集合 . 如果你看一下这里的文档:https://docs.oracle.com/cd/B28359_01/appdev.111/b28370/collections.htm#LNPLS00501

    您可以看到“关联数组”只是一个PL / SQL集合类型 .

    就“操作”而言,我基于规范的理解是它纯粹是位置记录本身的属性 . 我会做类似下面的事情:

    DECLARE 
      --declare your location record based on the spec
      TYPE location IS RECORD (
        location_id integer,
        operation VARCHAR2(1)
        --additional values from the spec would go here
      );
    
      --declare an array as a table of the location type
      TYPE location_array IS TABLE OF location INDEX BY BINARY_INTEGER;
    
      --two variables to hold the data
      example_location location;
      locations location_array;
    BEGIN 
      --start building your location record for the location you want to modify
      example_location.location_id := 1;
      example_location.operation   := 'T';
      --..... additional values here
    
      --add the location to the array
      locations(locations.count + 1) := example_location;
    
      --repeat the above for any other locations, or populate these some other way
    
      --loop through the locations
      FOR i IN locations.first..locations.last
      LOOP
        --decide the logic based on the operation, could just as easily use your if logic here
        CASE locations(i).operation
          WHEN 'U' THEN
            dbms_output.put_line('your update logic here');
          WHEN 'I' THEN
            dbms_output.put_line('your insert logic here');
          WHEN 'D' THEN
            dbms_output.put_line('your delete logic here');
          ELSE
            dbms_output.put_line('other operations');
        END CASE;
      END LOOP;
    END;
    

    您需要调整上述内容以满足您的需求,添加相关的逻辑,消息,提交,错误处理等 .

相关问题