Ask Your Question
1

How can I create an Oracle procedure that returns multiple results in a single column when needed?

asked 2023-05-23 13:02:34 +0000

lakamha gravatar image

edit retag flag offensive close merge delete

1 Answer

Sort by ยป oldest newest most voted
3

answered 2023-05-23 13:07:02 +0000

bukephalos gravatar image

One way to create an Oracle procedure that returns multiple results in a single column is to use a user-defined type (UDT) and a table of that type. Here's an example:

First, create a UDT to represent the multiple results:

CREATE TYPE result_type AS OBJECT (
  id NUMBER,
  name VARCHAR2(50)
);

Next, create a table of the UDT to hold the results:

CREATE TYPE result_table AS TABLE OF result_type;

Then, create the procedure that returns the results in a single column as follows:

CREATE PROCEDURE get_results (
  p_param1 IN VARCHAR2,
  p_param2 IN VARCHAR2,
  p_results OUT result_table
)
AS
BEGIN
  -- Perform some logic to get the results
  SELECT result_type(id, name)
  BULK COLLECT INTO p_results
  FROM some_table
  WHERE some_column = p_param1
  AND another_column = p_param2;
END;

In this example, the get_results procedure takes two input parameters (p_param1 and p_param2) and an output parameter (p_results). The procedure performs some logic to get the results from a table (some_table) and stores them in the p_results parameter using the BULK COLLECT INTO syntax.

Finally, you can call the procedure and retrieve the results:

DECLARE
  l_results result_table;
BEGIN
  get_results('value1', 'value2', l_results);
  FOR i IN 1..l_results.COUNT LOOP
    DBMS_OUTPUT.PUT_LINE(l_results(i).id || ' ' || l_results(i).name);
  END LOOP;
END;

In this example, the get_results procedure is called with some input values ('value1' and 'value2') and the results are stored in a local variable (l_results). The results can then be iterated over and displayed using the DBMS_OUTPUT.PUT_LINE procedure.

edit flag offensive delete link more

Your Answer

Please start posting anonymously - your entry will be published after you log in or create a new account. This space is reserved only for answers. If you would like to engage in a discussion, please instead post a comment under the question or an answer that you would like to discuss

Add Answer


Question Tools

Stats

Asked: 2023-05-23 13:02:34 +0000

Seen: 8 times

Last updated: May 23 '23