获取 PL/SQL 集合中元素的索引
是否有内置函数可以确定 PL/SQL 集合中元素的(第一个)索引?
就像
DECLARE
TYPE t_test IS TABLE OF VARCHAR2(1);
v_test t_test;
BEGIN
v_test := NEW t_test('A', 'B', 'A');
dbms_output.put_line( 'A: ' || get_index( v_test, 'A' ) );
dbms_output.put_line( 'B: ' || get_index( v_test, 'B' ) );
dbms_output.put_line( 'C: ' || get_index( v_test, 'C' ) );
END;
A: 1
B: 2
C:
我可以使用关联数组、嵌套表或变量数组,只要有必要。如果同一元素存在多次,则第一次出现的索引就足够了。
否则我必须做类似的事情
CREATE FUNCTION get_index ( in_test IN t_test, in_value IN VARCHAR2 )
RETURN PLS_INTEGER
AS
i PLS_INTEGER;
BEGIN
i := in_test.FIRST;
WHILE( i IS NOT NULL ) LOOP
IF( in_test(i) = in_value ) THEN
RETURN i;
END IF;
i := in_test.NEXT(i);
END LOOP;
RETURN NULL;
END get_index;
Is there a built-in function to determine the (first) index of an element in a PL/SQL collection?
Something like
DECLARE
TYPE t_test IS TABLE OF VARCHAR2(1);
v_test t_test;
BEGIN
v_test := NEW t_test('A', 'B', 'A');
dbms_output.put_line( 'A: ' || get_index( v_test, 'A' ) );
dbms_output.put_line( 'B: ' || get_index( v_test, 'B' ) );
dbms_output.put_line( 'C: ' || get_index( v_test, 'C' ) );
END;
A: 1
B: 2
C:
I can use Associative Arrays, Nested Tables or Varrays, whatever necessary. If the same element exists more than once, then the index of the first occurrence is sufficient.
Otherwise I'd have to do something like
CREATE FUNCTION get_index ( in_test IN t_test, in_value IN VARCHAR2 )
RETURN PLS_INTEGER
AS
i PLS_INTEGER;
BEGIN
i := in_test.FIRST;
WHILE( i IS NOT NULL ) LOOP
IF( in_test(i) = in_value ) THEN
RETURN i;
END IF;
i := in_test.NEXT(i);
END LOOP;
RETURN NULL;
END get_index;
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
不确定这是否真的有帮助,或者您是否认为它更优雅:
Not sure, if this really helps, or if you think it is more elegant:
我不认为有一个内置函数可以搜索集合。但是,如果您知道需要经常搜索集合,则可以构建索引。向集合中添加元素会稍微昂贵一些,但查找元素将是 O(1) 操作(而不是强力搜索的 O(n) 操作)。例如,您可以使用如下内容:
您还可以定义一个包含数组的记录,并且与数组交互的所有函数/过程都将使用此记录类型。
I don't think there is a built-in function that searches a collection. However, if you know you will need to search a collection a lot, you could build an index. Adding element to the collection will be a bit more expensive, but looking for an element will be an O(1) operation (instead of O(n) for a brute force search). For example, you could use something like this:
You could also define a record that contains both arrays and all functions/procedures to interact with arrays would use this record type.
如有疑问,请查阅文档 ;) (此处)
结果:
When in doubt, consult the documentation ;) (here)
Result: