简体   繁体   中英

Is there a way to create an Object type matching %rowtype of a table?

I need a schema level type (to reference it from c++ code) that will always be the same(same fields) as %rowtype record of a table. Sadly, I cannot use %rowtype directly from code and can only work with named types declared as

create type blabla is object...

Is there a way to create this in an automatic manner or will I have to manually create and support object type for each table I need this for?

Object types are schema-level database objects, which means that they must conform to SQL datatypes and syntax (except for those parts which are implemented in PL/SQL: the methods).

%ROWTYPE and %TYPE are both PL/SQL attributes and thus cannot be used when defining attributes of an object type.

I know - it bums me out, too.

If you need to create an object type that mirrors a table, for lots of tables, it will not be too difficult to write a generator with a query against user_tab_columns.

You can not use the %ROWTYPE in building an object type, but you can get the code to build types based on tables without manually scanning the table structure and writing the type.

Say you have tables like these:

create table someTypesTable( n   number(10),
                             n2  number(7, 3),
                             v   varchar2(16),
                             d   date, 
                             t   timestamp)

create table someOtherTypesTable( n number,
                                  c clob,
                                  t timestamp(3))

You can use USER_TAB_COLS ( or ALL_TAB_COLUMNS, DBA_TAB_COLUMNS, depending on your need) to get informations about the columns of these tables and build a piece of code that creates the types you need.

This could be a starting point, to be refined to handle the different types you may encounter in the tables:

select 'create or replace type tTab' || table_name ||
        ' as object ( ' ||
       listagg(
               column_name || ' ' ||
               data_type ||
               case when data_type = 'NUMBER' and data_precision is not null then '(' || data_precision || ',' || data_scale || ')'
                    when data_type = 'VARCHAR2' then '(' || data_length ||')'
               end
              , ', ' ) within group ( order by column_id) ||
       ')'
from user_tab_cols
where table_name in ('SOMETYPESTABLE', 'SOMEOTHERTYPESTABLE')
group by table_name

This gives, for the tables above, the following types:

CREATE OR REPLACE TYPE tTabSOMEOTHERTYPESTABLE AS OBJECT
(
    N NUMBER,
    C CLOB,
    T TIMESTAMP(3)
)

CREATE OR REPLACE TYPE tTabSOMETYPESTABLE AS OBJECT
(
    N NUMBER(10, 0),
    N2 NUMBER(7, 3),
    V VARCHAR2(16),
    D DATE,
    T TIMESTAMP(6)
)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM