0

I have a package in oracle. In the package i have a procedure which performs an (insert into ..select.. ) statement

which is like this:

insert into some_table(col1 , col2 , col3, col4)

select col1 , col2, my_func(col3) as new_col3 , col4

from some_other_table

my_func(col3) does some logic to return a value.

now i need to to return two values instead of one, using the same logic.

i can simply write another function to do the same logic and return the second value, but that would be expensive because the function selects from a large history table.

i can't do a join with the history table because the function doesn't perform a simple select.

is there a way to get two columns by calling this function only once?

1 Answer 1

3

Create an OBJECT type with two attributes and return that from your function. Something like:

SQL Fiddle

Oracle 11g R2 Schema Setup:

CREATE TYPE my_func_type IS OBJECT(
  value1 NUMBER,
  value2 VARCHAR2(4000)
);
/

CREATE FUNCTION my_func
RETURN my_func_type
IS
  value my_func_type;
BEGIN
  value := my_func_type( 42, 'The Meaning of Life, The Universe and Everything' );
  RETURN value;
END;
/

CREATE TABLE table1 (col1, col2, col5 ) AS
  SELECT 1, 2, 5 FROM DUAL
/

Query 1:

SELECT col1,
       col2,
       t.my_func_value.value1 AS col3,
       t.my_func_value.value2 AS col4,
       col5
FROM   (
  SELECT col1,
         col2,
         my_func() AS my_func_value,
         col5
  FROM   table1
) t

Results:

| COL1 | COL2 | COL3 |                                             COL4 | COL5 |
|------|------|------|--------------------------------------------------|------|
|    1 |    2 |   42 | The Meaning of Life, The Universe and Everything |    5 |
Sign up to request clarification or add additional context in comments.

6 Comments

@Nina - updated. You need to use a table name/alias when you reference the object attributes in the query.
Currently, you cannot define object types in a PL/SQL block, subprogram, or package.
1+ for "The Meaning of Life, The Universe and Everything"
@Nina You need to define the object type in the SQL scope (not in PL/SQL) if they are going to be used in SQL queries (in Oracle 11g and below - Oracle 12.something supports PL/SQL declared types in SQL).
@Nina why do you "need" the object type to be within the package? By creating the type at the schema level (i.e. create or replace object ...) you lose nothing and gain everything.
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.