Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to insert into oracle custom object from select result?

I have a obj like below

CREATE TYPE SOME_CUSTOM_OBJ FORCE AS OBJECT(
   ID number,
   Name varchar(30)
)

and want to insert value in that, I read the document for oracle database, but only way that I found is use initial function.

DECLARE
  SOME_OBJ SOME_CUSTOM_OBJ;
BEGIN
  SOME_OBJ := SOME_CUSTOM_OBJ(1,'PETER');
  DBMS_OUTPUT.PUT_LINE(SOME_OBJECT.ID);
END;

// OUTPUT : 1

I want to insert those value from another table, the imagine like below

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

DECLARE
  SOME_OBJECT SOME_CUSTOM_OBJECT;
BEGIN
  SOME_OBJECT := SOME_CUSTOM_OBJECT(
  SELECT ID,NAME FROM ANTHER_TABLE WHERE {SOME CONDITIONS} AND rownum = 1
);
  DBMS_OUTPUT.PUT_LINE(SOME_OBJECT.ID);
END;
// OUTPUT : 1

The value who select from table would be only 1 row.

If use Object_table could be easy to solve my question, but I don’t want to add too much things in the database.

>Solution :

You can use the object constructor in the SELECT clause:

DECLARE
  SOME_OBJECT SOME_CUSTOM_OBJ;
BEGIN
  SELECT some_custom_obj(ID,NAME)
  INTO   some_object
  FROM   another_table
  WHERE  rownum = 1;
  
  DBMS_OUTPUT.PUT_LINE(SOME_OBJECT.ID);
END;
/

Which, for the sample data:

CREATE TABLE another_table (id, name) AS
SELECT 1, 'Alice' FROM DUAL;

Outputs:

1

db<>fiddle here

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading