[英]Oracle PL/SQL - how to use table of varchar in select statement?
我有一個表類型聲明為
TYPE t_table IS TABLE OF VARCHAR2(15) INDEX BY PLS_INTEGER;
我試圖在帶有 select 語句的過程中使用它,但它不起作用:
procedure get_something (
p_in_list IN t_table,
p_out_list OUT t_table
)
IS
BEGIN
SELECT item
BULK collect into p_out_list
from my_table
where myrow in (select * from table(p_in_list));
END get_something;
我如何在 select... 聲明中使用它?
它在 19.0 中進行了測試。 我現在沒有早期版本可以測試,但我認為它至少需要 12.1。
首先,如果您需要類型為關聯數組(“索引依據”),則它需要符合 package 規范:
create or replace package demo_pkg
as
type t_table is table of varchar2(15) index by pls_integer;
end demo_pkg;
那么SQL就可以看到了:
declare
-- type t_table is table of varchar2(15) index by pls_integer;
subtype t_table is demo_pkg.t_table;
from_list t_table;
to_list t_table;
procedure get_something
( p_in_list in t_table
, p_out_list out t_table )
is
begin
select dummy bulk collect into p_out_list
from dual
where dummy in (select * from table(p_in_list));
end get_something;
begin
from_list(1) := 'X';
from_list(2) := 'Y';
from_list(3) := 'Z';
get_something(from_list, to_list);
end;
從 18c 開始,您可以使用限定表達式以聲明方式填充數組,例如:
from_list t_table := demo_pkg.t_table(1 => 'X', 2 => 'Y', 3 => 'Z');
要么
get_something
( demo_pkg.t_table(1 => 'X', 2 => 'Y', 3 => 'Z')
, to_list );
其中一些限制是因為關聯 arrays 並不是真正適合 SQL 查詢,並且對它們的支持需要一段時間才能添加。 如果將t_table
聲明為常規嵌套表,它應該可以在早期版本中使用:
create or replace package demo_pkg
as
type t_table is table of varchar2(15);
end demo_pkg;
或將其創建為獨立的 SQL object:
create or replace type t_table as table of varchar2(15);
這也使得構造member of
可能:
declare
from_list t_table := t_table('X','Y','Z');
to_list t_table;
procedure get_something
( p_in_list in t_table
, p_out_list out t_table )
is
begin
select dummy bulk collect into p_out_list
from dual
where dummy member of p_in_list;
end get_something;
begin
get_something(from_list, to_list);
end;
member of
僅適用於“嵌套表”collections,不適用於關聯 arrays 或 varrays。 我永遠無法真正理解 varrays 的意義,除非大小限制對您的業務邏輯非常有用,以至於您可以忍受所有丟失的功能。
這是一個選擇; 看看是否有幫助。
示例表和類型:
SQL> create table my_table as
2 select dname item, loc myrow from dept;
Table created.
SQL> create or replace type t_table as varray(20) of varchar2(20);
2 /
Type created.
程序:
SQL> create or replace procedure
2 get_something (
3 p_in_list in t_table,
4 p_out_list out t_table
5 )
6 is
7 begin
8 select item
9 bulk collect into p_out_list
10 from my_table
11 where myrow in (select * from table(p_in_list));
12 end get_something;
13 /
Procedure created.
SQL>
測試:
SQL> set serveroutput on
SQL> declare
2 l_in t_table;
3 l_out t_table;
4 begin
5 l_in := t_table();
6 l_in.extend(2);
7 l_in(1) := 'DALLAS';
8 l_in(2) := 'NEW YORK';
9
10 get_something(l_in, l_out);
11
12 for i in 1 .. l_out.count loop
13 dbms_output.put_line(l_out(i));
14 end loop;
15 end;
16 /
RESEARCH
ACCOUNTING
PL/SQL procedure successfully completed.
SQL>
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.