简体   繁体   English

PL/SQL 使用表变量作为查询表

[英]PL/SQL Use table variable as query table

In PL/SQL is it possible to use a variable as a query a table?在 PL/SQL 中是否可以使用变量作为查询表?

Tried:试过:

declare
   TYPE t_name IS TABLE OF varchar(50) INDEX BY PLS_INTEGER;
   v_names t_name;
begin
select name bulk collect into v_names from my_table;

select name from v_names where name = 'Max';
end;

Yes... but not how you are doing it, for two reasons:是的......但不是你是怎么做的,原因有两个:

  • Firstly, you do not have a collection (what you are calling a table variable) as you have used INDEX BY PLS_INTEGER so what you have is an associative array.首先,你没有一个集合(你称之为表变量),因为你使用了INDEX BY PLS_INTEGER所以你拥有的是一个关联数组。
  • Secondly, you can only use collections in SQL queries where the data type has been declared in the SQL scope (and yours is declared in PL/SQL). Secondly, you can only use collections in SQL queries where the data type has been declared in the SQL scope (and yours is declared in PL/SQL).

So, first you need to create the type:所以,首先你需要创建类型:

CREATE TYPE t_name IS TABLE OF VARCHAR2(50);

Then you can run the PL/SQL block:然后你可以运行 PL/SQL 块:

DECLARE
  v_names t_name;
  v_name  VARCHAR2(50);
BEGIN
  SELECT name
  BULK COLLECT INTO v_names
  FROM my_table;

  SELECT COLUMN_VALUE
  INTO   v_name
  FROM   TABLE(v_names)
  WHERE  COLUMN_VALUE = 'Max';
  
  DBMS_OUTPUT.PUT_LINE( v_name );
END;
/

(Note: the table collection expression in the second query has the pseudo-column COLUMN_VALUE rather than any particular identifier from a table.) (注意:第二个查询中的表集合表达式具有伪列COLUMN_VALUE而不是表中的任何特定标识符。)

db<>fiddle here db<> 在这里摆弄

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM