在Oracle函数中返回TABLE

时间:2018-08-17 12:53:52

标签: oracle

我想在选择时更新表的某些行,然后仅返回更新的行。我用过:

UPDATE RETURNING BULK COLLECT INTO 

它可以正确地用于更新行,但是当我在函数中使用它来返回更新的行时,就会发生Oracle异常。

您能否解释一下第一个功能为什么起作用但第二个功能不起作用的原因。

这是我的桌子的内容:

create table app.test (id number, col_to_update varchar2(20));

insert into app.test values (1, 'BOB');
insert into app.test values (2, 'PETER');
insert into app.test values (3, 'BOB');
insert into app.test values (4, 'PETER');
insert into app.test values (5, 'BOB');

自定义类型:

create or replace type emp_dets as OBJECT (id INT,col_to_update VARCHAR2(60));
create or replace type emp_dets_nt as table of emp_dets;

和两个功能:

create or replace function get_emp_dets
    return emp_dets_nt
as
    return_value emp_dets_nt;
BEGIN
    return_value:=emp_dets_nt(); 
    select emp_dets(ID, col_to_update)
    bulk collect into return_value
    from app.TEST;
    return return_value;
end;

create or replace function get_emp_dets
    return emp_dets_nt
as
    return_value emp_dets_nt;
BEGIN
return_value:=emp_dets_nt(); 
    UPDATE app.TEST
SET col_to_update = 'UPDATED'
WHERE col_to_update = 'BOB'
    RETURNING emp_dets(id, col_to_update)
    BULK COLLECT INTO return_value;
    return return_value;
end;

1 个答案:

答案 0 :(得分:0)

使用该功能作为实用的自主事务进行尝试

create or replace function get_emp_dets
    return emp_dets_nt
as
pragma autonomous_transaction;
    return_value emp_dets_nt;
BEGIN
return_value:=emp_dets_nt(); 
    UPDATE app.test
SET col_to_update = 'UPDATED'
WHERE col_to_update = 'BOB'
    RETURNING emp_dets(id, col_to_update)
    BULK COLLECT INTO return_value;
    commit;
    return return_value;
end;