Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Create a copy of a table within the same database DB2

Tags:

copy

aix

db2

Is there an easy way to copy a table to the same database of course with different name. I tried some of these listed below,

db2 "CREATE TABLE SCHEMA.NEW_TB COPY AS SELECT * FROM SCHEMA.OLD_TB WHERE 1 = 2"

db2 "SELECT INTO SCHEMA.NEW_TB FROM SCHEMA.OLD_TB"

db2 "SELECT * FROM SCHEMA.OLD_TB INSERT INTO SCHEMA.NEW_TB"

None of these worked I am using db2 v9.5

like image 465
Govind Kailas Avatar asked Jul 10 '12 15:07

Govind Kailas


People also ask

How do I copy a table in the same database?

In Object Explorer, right-click Tables and select New Table. In Object Explorer right-click the table you want to copy and select Design. Select the columns in the existing table and, from the Edit menu, select Copy. Switch back to the new table and select the first row.

What is clone table in Db2?

The clone table will be structurally identical to the base table in every way: same number of columns, column names, data types, as well as have the same indexes, before triggers, LOB objects and so on. All of this is done auto-magically by DB2 when it the clone table is created.

Can you duplicate a table?

To copy the table, press CTRL+C.


2 Answers

You have to surround the select part with parenthesis.

CREATE TABLE SCHEMA.NEW_TB AS (     SELECT *     FROM SCHEMA.OLD_TB ) WITH NO DATA 

Should work. Pay attention to all the things @Gilbert said would not be copied.

I'm assuming DB2 on Linux/Unix/Windows here, since you say DB2 v9.5.

like image 177
bhamby Avatar answered Oct 31 '22 02:10

bhamby


Try this:

CREATE TABLE SCHEMA.NEW_TB LIKE SCHEMA.OLD_TB; INSERT INTO SCHEMA.NEW_TB (SELECT * FROM SCHEMA.OLD_TB); 

Options that are not copied include:

  • Check constraints
  • Column default values
  • Column comments
  • Foreign keys
  • Logged and compact option on BLOB columns
  • Distinct types
like image 43
Gilbert Le Blanc Avatar answered Oct 31 '22 00:10

Gilbert Le Blanc