Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to SELECT from object type column in Oracle 11g?

Hy guys, I have following two Oracle objects:

CREATE OR REPLACE TYPE car AS OBJECT( 
name VARCHAR( 80 ) 
) NOT FINAL;

And also, there is another object:

CREATE OR REPLACE TYPE truck UNDER car ( 
doors NUMBER,
seats NUMBER 
);

There is also following table:

CREATE TABLE vehicles (
id NUMBER NOT NULL,
vehicle car,
PRIMARY KEY (id)
);

Here is some data:

INSERT INTO vehicles ( id, vehicle ) VALUES ( 1, truck( 'ford', 4, 4 ) );
INSERT INTO vehicles ( id, vehicle ) VALUES ( 2, truck( 'toyota', 4, 5 ) );

Finally, my question is: How to select only number of doors and number of seats from vehicle table column?

I tried following but it does not work:

SELECT v.vehicle.doors AS doors AS seats FROM vehicles v;

I got following error:

ORA-00904: "V"."VEHICLE"."DOORS": invalid identifier

Only parameter that i can get without any error is one from car object.

FYI, I am using Oracle 11g on CentOS 6.2

Cheers, Bojan

like image 366
Bojan Bijelić Avatar asked Apr 25 '12 14:04

Bojan Bijelić


People also ask

What is object type type in Oracle?

An object type is a kind of data type. You can use it in the same ways that you use standard data types such as NUMBER or VARCHAR2 . For example, you can specify an object type as the data type of a column in a relational table, and you can declare variables of an object type.

How do I select a specific column in Oracle?

The Oracle SELECT clause:After the Oracle SELECT keyword, specify the names of the columns that you would like to retrieve, separated by comma (,). You can specify as many columns as you want; you can even specify the same column more than once. The columns appear in the order selected.

What is the reference object of a column?

A REF column may be constrained with a REFERENTIAL constraint similar to the specification for foreign keys. The rules for referential constraints apply to such columns. That is, the object reference stored in these columns must point to a valid and existing row object in the specified object table.

What is object datatype in SQL?

An object type differs from native SQL datatypes in that it is user-defined, and it specifies both the underlying persistent data (attributes) and the related behaviors (methods). Object types are abstractions of the real-world entities, for example, purchase orders.


1 Answers

You need to use the TREAT function to get the database engine to treat VEHICLE as a TRUCK, as in:

SELECT ID, TREAT(vehicle AS TRUCK).DOORS FROM VEHICLES

Share and enjoy.

like image 197