¿Cómo puedo crear una copia de una tabla Oracle sin copiar los datos?


Conozco la declaración:

create table xyz_new as select * from xyz;

Que copia la estructura y los datos, pero ¿qué pasa si solo quiero la estructura?

Author: Christopher Rapcewicz, 2008-10-24

15 answers

Simplemente use una cláusula where que no seleccione ninguna fila:

create table xyz_new as select * from xyz where 1=0;

Limitaciones

Las siguientes cosas no se copiarán a la nueva tabla:

  • secuencias
  • desencadenantes
  • índices
  • algunas restricciones no se pueden copiar
  • materializado ver registros

Esto tampoco maneja particiones


 370
Author: Jim Hudson,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2017-09-28 08:52:49

Usé el método que aceptaste mucho, pero como alguien señaló, no duplica las restricciones (a excepción de NOT NULL, creo).

Un método más avanzado si desea duplicar la estructura completa es:

SET LONG 5000
SELECT dbms_metadata.get_ddl( 'TABLE', 'MY_TABLE_NAME' ) FROM DUAL;

Esto le dará el texto completo de la instrucción create que puede modificar como desee para crear la nueva tabla. Tendría que cambiar los nombres de la tabla y todas las restricciones, por supuesto.

(También podría hacer esto en versiones anteriores utilizando EXP / IMP, pero ahora es mucho más fácil.)

Edited to add Si la tabla que buscas está en un esquema diferente:

SELECT dbms_metadata.get_ddl( 'TABLE', 'MY_TABLE_NAME', 'OTHER_SCHEMA_NAME' ) FROM DUAL;
 80
Author: Dave Costa,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2013-07-15 13:16:51

Usando sql developer seleccione la tabla y haga clic en la pestaña DDL

Puede usar ese código para crear una nueva tabla sin datos cuando la ejecute en una hoja de trabajo sql

Sqldeveloper es una aplicación gratuita de oracle.

Si la tabla tiene secuencias o disparadores, el ddl a veces también los generará para usted. Solo tienes que tener cuidado en qué orden los haces y saber cuándo encender o apagar los gatillos.

 14
Author: branchgabriel,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2008-10-24 17:26:24
create table xyz_new as select * from xyz where rownum = -1;

Para evitar iterar una y otra vez e insertar nada basado en la condición donde 1=2

 11
Author: sunleo,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2013-12-23 21:08:33
    DECLARE
    l_ddl   VARCHAR2 (32767);
BEGIN
    l_ddl      := REPLACE (
                      REPLACE (
                          DBMS_LOB.SUBSTR (DBMS_METADATA.get_ddl ('TABLE', 'ACTIVITY_LOG', 'OLDSCHEMA'))
                        , q'["OLDSCHEMA"]'
                        , q'["NEWSCHEMA"]'
                      )
                    , q'["OLDTABLSPACE"]'
                    , q'["NEWTABLESPACE"]'
                  );

    EXECUTE IMMEDIATE l_ddl;
END; 
 4
Author: Brian Leach,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2016-12-05 19:17:52

Puedes hacer esto Create table New_table as select * from Old_table where 1=2 ; pero ten cuidado La tabla que crea la dosis no tiene ningún índice, Pk y así sucesivamente como la old_table

 3
Author: Mohsen Molaei,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2015-12-10 23:14:18
SELECT * INTO newtable
FROM oldtable
WHERE 1 = 0;

Cree una nueva tabla vacía usando el esquema de otra. Simplemente agregue una cláusula WHERE que haga que la consulta no devuelva datos:

 2
Author: guesswho,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2017-08-31 23:21:21

Simplemente escribe una consulta como:

create table new_table as select * from old_table where 1=2;

Donde new_table es el nombre de la nueva tabla que desea crear y old_table es el nombre de la tabla existente cuya estructura desea copiar, esto copiará solo la estructura.

 1
Author: user3284249,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2014-02-07 14:52:13

WHERE 1 = 0 o condiciones falsas similares funcionan, pero no me gusta cómo se ven. Código marginalmente más limpio para Oracle 12c + IMHO es

CREATE TABLE bar AS SELECT * FROM foo FETCH FIRST 0 ROWS ONLY;

Se aplican las mismas limitaciones: solo las definiciones de columna y su nullability se copian en una nueva tabla.

 1
Author: DKroot,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2018-02-16 17:02:52

También puede hacer un

create table abc_new as select * from abc; 

Luego trunca la tabla abc_new. Espero que esto sea suficiente para su requerimiento.

 0
Author: Digo,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2012-08-28 22:23:05
Create table target_table 
As
Select * 
from source_table 
where 1=2;

Source_table es la tabla de la que u quiere copiar la estructura.

 0
Author: Prashant Mishra,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2015-04-21 05:51:56

Usando pl/sql developer puede hacer clic con el botón derecho en el nombre_de_ tabla ya sea en el espacio de trabajo sql o en el explorador de objetos, luego haga clic en "ver" y luego haga clic en "ver sql" que genera el script sql para crear la tabla junto con todas las restricciones, índices, particiones, etc..

A continuación se ejecuta el script usando el nombre_nuevo

 0
Author: Yariv Scheingut,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2015-06-11 08:36:12

De otra manera, puede obtener ddl de la creación de la tabla desde el comando que se muestra a continuación y ejecutar la creación.

SELECT DBMS_METADATA.GET_DDL('TYPE','OBJECT_NAME','DATA_BASE_USER') TEXT FROM DUAL 

TYPE is ('TABLE','PROCEDURE', etc...)

Con este comando puede obtener la mayoría de ddl de objetos de base de datos.

 0
Author: Diogo Maschio,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2015-11-18 15:02:31

Copia sin datos del cuadro

create table <target_table> as select * from <source_table> where 1=2;

Copiar con los datos de la tabla

create table <target_table> as select * from <source_table>;
 0
Author: Alok,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2017-04-16 14:07:26

La tarea anterior se puede completar en dos sencillos pasos.

PASO 1:

CREATE table new_table_name AS(Select * from old_table_name);

El query anterior crea un duplicado de una tabla (con el contenido también).

Para obtener la estructura, elimine el contenido de la tabla usando.

PASO 2:

DELETE * FROM new_table_name.

Espero que esto resuelva su problema. Y gracias a los mensajes anteriores. Me dio mucha información.

 -4
Author: Donkha,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2012-08-28 21:50:00