"PLS-00526: A MAP or ORDER function is required" 比较对象是否相等

"PLS-00526: A MAP or ORDER function is required" when comparing objects for equality

在 Oracle 11gR2 上,我创建了一个简单的 PL/SQL 对象类型。尝试比较 equality/inequality 的两个实例时,我收到 PLS-00526: A MAP or ORDER function is required for comparing objects in PL/SQL 错误,即使 Oracle documentation 明确指出

If neither a MAP nor an ORDER method is specified, then only comparisons for equality or inequality can be performed.

这是我用来重现错误的 PL/SQL 代码示例:

create or replace type point_t is object (x number, y number);
/

declare
  p1 point_t := point_t(1, 2);
  p2 point_t := point_t(1, 2);
  p3 point_t := point_t(2, 1);
begin
  dbms_output.put_line('p1 = p1 ' || case when p1 = p1 then 'OK' else 'FAIL' end);
  dbms_output.put_line('p2 = p1 ' || case when p2 = p1 then 'OK' else 'FAIL' end);
  dbms_output.put_line('p3 <> p1 ' || case when p3 <> p1 then 'OK' else 'FAIL' end);
end;
/

是的,如果既没有指定 MAP 也没有指定 ORDER 方法,您可以比较对象的相等性或不相等性但只能在 SQL 语句中,而不是 PL/SQL 块直接地。

引自Database Object-Relational Developer's Guide

if you do not declare one of these methods, you can only compare objects in SQL statements, and only for equality or inequality.

create or replace type point_t is object (x number, y number);
/

select case
        when point_t(1,1) = point_t(1,1) then 'OK'
        else 'FAIL'
       end as cmp_res
  from dual;


set serveroutput on;
declare
  l_p1 point_t := point_t(1,2);
  l_p2 point_t := point_t(1,2);
  l_res varchar2(7) := 'OK';
begin
  select 'FAIL'
    into l_res
   from dual
  where l_p1 != l_p2;  -- put it in the where clause just for the sake 
                       -- of demonstration. Can do comparison in the 
                       -- select list as well.
  dbms_output.put_line('p1 = p2 : ' || l_res);
end;

结果:

Type created.

CMP_RES
-------
OK     

1 row selected.

p1 = p2 : FAIL
PL/SQL procedure successfully completed.

但如果需要直接在PL/SQL块中比较对象,则需要定义对象比较规则(当一个对象为equal/unequal,大于或小于其他对象时,尤其是当对象有很多属性)需要实现 MAPORDER 方法。