将 PLSQL 函数修改为来自同一列的 return 多行

Modifying PLSQL function to return multiple rows from same column

我是初级 PLSQL 用户,我有一个可能相当简单的问题。

我创建了以下 SQL 函数,它 return 是进程的创建日期,其公司 ID 与我提供的公司 ID 匹配。我已将此连接到我的 JDBC,它的 return 值很好。

但是,我刚刚意识到我忽略了一个重要问题——完全有可能不止一个进程具有与我输入的 ID 值相匹配的公司 ID,在这种情况下,我将需要能够访问 ID return 匹配的所有创建日期值。

CREATE OR REPLACE FUNCTION FUNCTION_1(
    c_id IN INT)
  RETURN INT
AS
  p_date process.date_created%TYPE;
BEGIN
  SELECT process.date_created
  FROM PROCESS
  WHERE process.corporate_id = c_id
  ORDER BY process.corporate_id;
  RETURN p_id;
END FUNCTION_1;
/

有没有一种方法可以将我的函数修改为来自同一列的 return 多行,然后使用 JDBC 将该函数调用到 return 某种数组?或者,如果那不可能,有没有办法可以 return 使用 PLSQL 程序或简单的 SQL 结合 JDBC 来满足我的需求?我在这里查看了其他问题,但 none 似乎正是我需要知道的。

感谢任何能提供帮助的人!

您需要对函数进行一些更改。 java 方面会很简单 select

  • 您需要将函数类型从 int 更改为 collection 在此处阅读 table 函数 Table Functions
  • user oracle table() 函数将函数的结果转换为 table 它允许您在查询中使用您的函数。在此处阅读有关语法的更多信息:Table Collections: Examples

此处示例如何从 java 调用您的函数:

select t.column_value as process_id 
      from  table(FUNCTION_1(1)) t

--result
    PROCESS_ID
1   1
2   2


--we need create new type - table of integers
CREATE OR REPLACE TYPE t_process_ids IS TABLE OF int;

--and make changes in function
CREATE OR REPLACE FUNCTION FUNCTION_1(
    c_id IN INT)
  RETURN t_process_ids
AS
  l_ids  t_process_ids := t_process_ids();
BEGIN
  --here I populated result of select into the local variables
  SELECT process.id
  bulk collect into l_ids
  FROM PROCESS
  WHERE process.corporate_id = c_id
  ORDER BY process.corporate_id;

  --return the local var
  return l_ids;
END FUNCTION_1;

--the script that I used for testing
create table process(id int, corporate_id int, date_created date);
insert into process values(1, 1, sysdate);
insert into process values(2, 1, sysdate);
insert into process values(3, 2, sysdate);