sqloracle-databasescriptgenerate

Get all tables creation scripts from Oracle database


I have an Oracle db with a lot of tables and a lot of properties like: primary key,Unique key, Foreign key,Indexes, Privileges and partitions.

I need to create the same tables with the same properties in new Oracle db. Is there a way to generate a single creation script for all tables in my database?

Thanks


Solution

  • Yes. You can execute below query and the content in 'Definition' column is a CLOB which contains the DDL for the corresponding object

    SELECT OBJECT_TYPE,
           OBJECT_NAME,
           DBMS_METADATA.GET_DDL(OBJECT_TYPE, OBJECT_NAME) DEFINITION
      FROM DBA_OBJECTS
     WHERE OWNER = 'OWNER_NAME'
       AND OBJECT_TYPE IN ('FUNCTION',
                           'PACKAGE',
                           'PROCEDURE',
                           'SEQUENCE',
                           'TABLE',
                           'TRIGGER',
                           'VIEW')
     ORDER BY OBJECT_TYPE, OBJECT_NAME
    

    Below is a quick VB Script which helps extract the CLOBs

    folder = "Folder_name"
    connStr="<Your connection string here>"
    if fetchFromDB=true then
        set c=CreateObject("ADODB.Connection")
        c.ConnectionString=connStr
        c.Open
    
        set r=CreateObject("ADODB.recordset")
    
        sql="SELECT OBJECT_TYPE, OBJECT_NAME, DBMS_METADATA.GET_DDL(OBJECT_TYPE,OBJECT_NAME) DEFINITION FROM DBA_OBJECTS WHERE OWNER='<OWNER_NAME_HERE>' AND OBJECT_TYPE IN ('FUNCTION', 'PACKAGE', 'PROCEDURE', 'SEQUENCE', 'TABLE', 'TRIGGER', 'VIEW') ORDER BY OBJECT_TYPE, OBJECT_NAME"
        r.open sql,c,3,1
        dim fs,f
        set fs=CreateObject("Scripting.FileSystemObject")
        do until r.EOF
            set f=fs.OpenTextFile(folder & "\\" & r("OBJECT_TYPE") & "_" & r("OBJECT_NAME") & ".sql",8,true)
            f.WriteLine r("DEFINITION")
            r.MoveNext
            f.close
        loop
        r.close
    end if