PLSQL过程,以检查值是否包含在嵌套表中

时间:2019-01-18 11:44:57

标签: oracle stored-procedures plsql

我有一个简单的“包含”检查问题。就像在Java中一样 collection.contains(x)。我尝试了我们的EXISTS和MEMBER OF,但没有成功。

到目前为止,这是我的程序

PROCEDURE merge_custom_fields(s1_cf IN custom_fields_table, s2_cf IN custom_fields_table, r_cf OUT custom_fields_table) AS
  BEGIN
      IF(s1_cf IS NOT NULL AND s1_cf .count>0) THEN
        FOR idx IN s1_cf .first..s1_cf .last
        LOOP
         //---> s1_cf(idx).field_id contains in s2_cf <----
            r_cf .extend;
            r_cf (r_cf .last) := s1_cf (idx);
          END IF;
        END LOOP;
      END IF;
    END IF;
  END merge_custom_fields;

此处有其他信息

create or replace TYPE custom_fields_table FORCE
IS
  TABLE OF custom_fields_struct ;

这是custom_fields_struct的定义

create or replace TYPE custom_fields_struct FORCE
AS
OBJECT
(
 field_id VARCHAR2 (128 CHAR),
 field_value TIMESTAMP (3)) FINAL ;

2 个答案:

答案 0 :(得分:0)

由于只需要获取具有公共field_id的元素,因此可以使用TABLE函数并进行连接。

DECLARE

     l_field_value   TIMESTAMP := systimestamp;
     s1_cf           custom_fields_table := custom_fields_table(
     custom_fields_struct(1,l_field_value),custom_fields_struct
     (2,l_field_value) );
     s2_cf           custom_fields_table := custom_fields_table(
     custom_fields_struct(2,l_field_value),custom_fields_struct
     (3,l_field_value) );
     r_cf  custom_fields_table;
BEGIN

SELECT custom_fields_struct(s1.field_id,s1.field_value) --should convert it to object
  BULK COLLECT INTO r_cf --load directly into your OUT collection
FROM   TABLE ( s1_cf ) s1
  JOIN TABLE ( s2_cf ) s2 
ON s1.field_id = s2.field_id; -- This filters the common elements

for i in r_cf.first..r_cf.last 
LOOP
  dbms_output.put_line(r_cf(i).field_id||','||r_cf(i).field_value);
  END LOOP;
END;
/

2,18-01-19 06:27:55.607 PM


PL/SQL procedure successfully completed.
可以使用

EXISTSMEMBER OF,但我想您想进行列与列的比较,而不是按元素进行比较。因此,我唯一想到的另一种选择是在两个集合上运行一个for循环,然后将一个集合的field_id与另一个集合进行比较,以获取该字段的索引。但是,考虑到您的要求,以上选项应该足够好。

您的过程如下:

CREATE OR REPLACE PROCEDURE merge_custom_fields (
     s1_cf   IN custom_fields_table,
     s2_cf   IN custom_fields_table,
     r_cf    OUT custom_fields_table
)
     AS
BEGIN
     SELECT custom_fields_struct(s1.field_id,s1.field_value) BULK COLLECT
     INTO r_cf
       FROM TABLE ( s1_cf ) s1
     JOIN   TABLE ( s2_cf ) s2 ON s1.field_id = s2.field_id;
END merge_custom_fields;
/

Demo

答案 1 :(得分:0)

可能是:

CREATE OR REPLACE PROCEDURE merge_custom_fields (
     s1_cf   IN custom_fields_table,
     s2_cf   IN custom_fields_table,
     r_cf    OUT custom_fields_table
)
     AS
BEGIN
     r_cf := s1_cf MULTISET UNION s2_cf;
END merge_custom_fields;
/

screenshot demo