首页 > 解决方案 > 获取 PL/SQL 集合中特定元素的键或索引?

问题描述

我们如何找到我们知道值的键或索引?例如,如果我们知道集合中存储的值是' Alex ',我们如何才能找到它存储在哪个索引或键中?

标签: oracleplsql

解决方案


索引是您引用集合中特定条目的方式。但是要获得具有条目值的索引,您需要迭代集合。

declare
  type some_collection is  table of integer;
  the_collection some_collection :=
                 some_collection( 4,84,32,97,2,92,3);
  target_value integer := &target_value;
  index_for_some_value integer;
  current_index integer;
begin
   current_index := the_collection.first;  
   while current_index is not null 
     and index_for_some_value is null
   loop
       if the_collection(current_index) = target_value
       then
           index_for_some_value := current_index;
       end if;
       current_index :=the_collection.next(current_index); 
   end loop;

   dbms_output.put_line( 'Target_Value ' || to_char(target_value)
                        || case when index_for_some_value is null
                                then ' not found.'
                                else ' found at index ' || to_char(index_for_some_value) || '.'
                           end
                        );
end;

当然,确切的代码可能取决于集合类型和索引类型。


推荐阅读