SQL create table use %type at column

declaration, oracle, sql

Solution

Based on your updated requirements, to create a table based on the types in these two tables:

create table t1 (col1 number, col2 varchar2(2), col3 date);
create table t2 (col1 varchar2(10 char));

You can just join them together, with a filter that always evaluates to false as Orangecrush suggested:

create table tb tablespace users as
select t1.col1 as col1, t1.col2 as col2, t1.col3 as col3,
    t1.col3 as col4, t2.col1 as col5, cast(null as varchar2(12 byte)) as col6
from t1
cross join t2
where null is not null;

Normally a `cross join` would be unwelcome, but the optimizer is clever enough to realise that the filter means it doesn't need to actually hit the tables at all. You can use a normal inner join if there are fields you can join on though, of course.

desc tb

Name Null Type              
---- ---- ----------------- 
COL1      NUMBER            
COL2      VARCHAR2(2)       
COL3      DATE              
COL4      DATE               -- new column with same type as t1.col3
COL5      VARCHAR2(10 CHAR)  -- column from other table
COL6      VARCHAR2(12)       -- new column with fixed type

Problem

I'm trying to create a backuptable of one of my tables (in a function), ``` CREATE TABLE TBTestBackup ( colum1 user.TBTest.colum1%type, colum2 user.TBTest.colum2%type, colum3 user.TBTest.colum3%type colum31 user.TBTest.colum3%type, --new column with same type as colum3 colum4 user.TBTest2.column15type, --column from other table colum4 CHAR (12 BYTE), --new column with fixed type ) TABLESPACE user_DATA ``` But I red this won't work, now my question is how could I make this as much dynamic as possible so I don't have to update the datatypes at the backup script every time I change a datatype e.g. from: `VARCHAR2(24 CHAR)` to `VARCHAR2(50 CHAR)` (the table-columns are fixed they wont change) this doesn't happen often but we had to do it some times because the field wasn't great enough for a specific value and then nobody updated the backup-table and id gave some errors. EDIT: I forgot something necessary: - I have to add 2 columns that aren't in the original table, but should have the same datatype as one of the already existing tables. could I use select as so it will have the same type but another name? if yes how do I do that? - and some fields that are from a different table (so I have to use joins) SUM: - Multiple columns with type from multiple tables - New Column with fixed Type - New Column with variable type like colum XY from table ABC

Original source