暂无图片
暂无图片
暂无图片
暂无图片
暂无图片

Oracle 使用集合进行合并

ASKTOM 2019-02-08
248

问题描述

嗨,汤姆,

我只是想了解表格函数是否可以与集合一起使用。
请找到我下面的代码。

脚本:

create table setm_students (id number, name varchar2(10));
create table setm_students_target as select * from setm_students where 1=2;

create or replace package pkg_test is
TYPE ty_rec_students is record  (id number, name varchar2(10));
TYPE ty_tb_ar_students is table of ty_rec_students index by pls_integer;
end;
/


declare 
l_tb_ar_students pkg_test.ty_tb_ar_students;
l_tb_ar_students_dummy pkg_test.ty_tb_ar_students;
begin
l_tb_ar_students := pkg_test.ty_tb_ar_students(1=>pkg_test.ty_rec_students(1, 'mike'),
                                               2=>pkg_test.ty_rec_students(2, 'John'),
                                               3=>pkg_test.ty_rec_students(3, 'Sara'),
                                               4=>pkg_test.ty_rec_students(4, 'Tim'),
                                               5=>pkg_test.ty_rec_students(5, 'Brian'));
dbms_output.put_line('Collection count normal '||l_tb_ar_students.count);
begin
select * bulk collect into l_tb_ar_students_dummy --this select from tbl works
from table(l_tb_ar_students);
dbms_output.put_line('Collection count test'||l_tb_ar_students_dummy.count);
/*merge into setm_students_target tar
using (select * from table(l_tb_ar_students)) src  --does not work
on (src.id = tar.id)
when not matched then
insert values (src.id,  src.name); */
exception
WHEN OTHERS THEN
dbms_output.put_line('ALERT '||SQLERRM||' TRACE '||DBMS_UTILITY.FORMAT_ERROR_BACKTRACE );
end;
end;
/
复制


table函数中的select语句工作。
使用表函数的合并会引发 “无效数据类型” 错误。这是因为使用的表函数是sql,而我还没有将其收集到本地集合中吗?

请让我知道,如何在MERGE语句中使用集合使用表函数。
请原谅我的无知。

提前谢谢!!

专家解答

您不能在非查询DML中使用PL/SQL数组作为表函数 (插入/更新/删除/合并)。您需要使用对象类型代替:

create or replace type ty_rec_students as object (
  id number, name varchar2(10)
);
/
create or replace type ty_tb_ar_students 
  is table of ty_rec_students;
/

declare
  l_tb_ar_students ty_tb_ar_students;
begin
  l_tb_ar_students := ty_tb_ar_students (
    ty_rec_students(1, 'mike'),
    ty_rec_students(2, 'John'),
    ty_rec_students(3, 'Sara'),
    ty_rec_students(4, 'Tim'),
    ty_rec_students(5, 'Brian')
  );
                                               
  dbms_output.put_line('Collection count normal '||l_tb_ar_students.count);

  merge into setm_students_target tar
  using (
    select * from table(l_tb_ar_students)
  ) src  
  on (src.id = tar.id)
  when not matched then
    insert values (src.id,  src.name); 

end;
/

select * from setm_students_target;

ID   NAME    
   1 mike    
   4 Tim     
   2 John    
   3 Sara    
   5 Brian 
复制

文章转载自ASKTOM,如果涉嫌侵权,请发送邮件至:contact@modb.pro进行举报,并提供相关证据,一经查实,墨天轮将立刻删除相关内容。

评论