使用oracle pl/sql在对象中循环

jgzswidk  于 2023-04-11  发布在  Oracle
关注(0)|答案(3)|浏览(171)

下面的代码作为对象调用MY_TYPE,用于循环到执行更新。

CREATE OR REPLACE PROCEDURE OTTWEB.MY_PROCEDURE (
    MY_ARRAY IN MY_TYPE
)
IS
BEGIN
FOR i IN 1..MY_ARRAY.COUNT LOOP
        UPDATE BULKSMSDETAILS SET STATUS = MY_ARRAY(i).STATUS, REMARKS = MY_ARRAY(i).REMARKS WHERE ID = MY_ARRAY(i).ID;
    END LOOP;
END;

取消打包以编译上述sp。错误消息:PLS-00302:必须声明组件“COUNT”
下面是对象

CREATE OR REPLACE TYPE OTTWEB.MY_TYPE AS OBJECT
(
 ID VARCHAR2(1000),
 STATUS NUMBER,
 REMARKS VARCHAR2(1000)
);
6ioyuze2

6ioyuze21#

举个例子。
首先键入:

SQL> create or replace type t_myt_row as object
  2    (id      number,
  3     status  varchar2(1),
  4     remark  varchar2(10)
  5    );
  6  /

Type created.

SQL> create or replace type my_type is table of t_myt_row;
  2  /

Type created.

样品表:

SQL> create table bulksmsdetails as
  2    select 1 id, 'A' status, 'Rem 1' remark from dual union all
  3    select 2, 'B', 'Rem 2' from dual union all
  4    select 3, 'A', 'Rem 3' from dual;

Table created.

程序:

SQL> create or replace procedure my_procedure
  2    (my_array in my_type)
  3  is
  4  begin
  5    dbms_output.put_line('Count = ' || my_array.count);
  6
  7    for i in 1 .. my_array.count loop
  8      update bulksmsdetails set
  9        status = my_array(i).status,
 10        remark = my_array(i).remark
 11      where id = my_array(i).id;
 12      dbms_output.put_line('ID = ' || my_array(i).id ||', updated ' ||sql%rowcount ||' row(s)');
 13    end loop;
 14  end;
 15  /

Procedure created.

测试:

SQL> set serveroutput on
SQL> declare
  2    l_tab my_type := my_type();
  3  begin
  4    l_tab.extend;
  5    l_tab(1) := t_myt_row(1, 'X', 'Rem X');
  6    l_tab.extend;
  7    l_tab(2) := t_myt_row(2, 'Y', 'Rem Y');
  8
  9    my_procedure(l_tab);
 10  end;
 11  /
Count = 2
ID = 1, updated 1 row(s)
ID = 2, updated 1 row(s)

PL/SQL procedure successfully completed.

结果:

SQL> select * from bulksmsdetails;

        ID S REMAR
---------- - -----
         1 X Rem X
         2 Y Rem Y
         3 A Rem 3

SQL>
kuuvgm7e

kuuvgm7e2#

MY_TYPE是一种对象类型,而不是集合类型。为了使用COUNT方法并循环遍历元素,您需要基于对象类型MY_TYPE创建一个集合类型(嵌套表或varray)。

CREATE OR REPLACE TYPE OTTWEB.MY_TYPE_TABLE AS TABLE OF MY_TYPE;

修改该过程以接受MY_TYPE_TABLE作为输入参数:

CREATE OR REPLACE PROCEDURE OTTWEB.MY_PROCEDURE (
    MY_ARRAY IN MY_TYPE_TABLE
)
IS
BEGIN
    FOR i IN 1..MY_ARRAY.COUNT LOOP
        UPDATE BULKSMSDETAILS
        SET STATUS = MY_ARRAY(i).STATUS, REMARKS = MY_ARRAY(i).REMARKS
        WHERE ID = MY_ARRAY(i).ID;
    END LOOP;
END;

它应该能够成功编译,并且可以使用MY_TYPE对象的嵌套表来更新BULKSMSDETAILS。

mw3dktmi

mw3dktmi3#

你不需要循环,例如你可以使用合并

create or replace procedure my_procedure(my_array in my_type)
is
begin
    merge into t_myt tgt
    using (select * from table(my_array)) src
    on (src.id =  tgt.id)
    when matched then
        update set status = src.status,
        remark = src.remark
    ;
end;

相关问题