【问题标题】:Getting the key or index of a specific element in a PL/SQL collection?获取 PL/SQL 集合中特定元素的键或索引?
【发布时间】:2021-03-20 14:44:31
【问题描述】:

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

【问题讨论】:

  • 在 PL/SQL 中,“集合”是三个不同(且完全不同)数据类型的统称:关联数组varray ,和嵌套表。很可能,您的问题的答案将取决于您所谈论的特定类型的“收藏”。 (其实严格来说,对于嵌套表来说,应该没有“索引”或“键”;之所以有索引,是因为PL/SQL的概念实现,而在我看来,用户可以访问索引的事实是 PL/SQL 的错误。)所以,请澄清。

标签: oracle plsql


【解决方案1】:

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

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;

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

【讨论】:

    猜你喜欢
    • 2011-06-16
    • 2018-05-02
    • 1970-01-01
    • 2019-05-08
    • 1970-01-01
    • 1970-01-01
    • 2012-11-21
    • 2013-05-24
    • 1970-01-01
    相关资源
    最近更新 更多