Copy table structure to new table in sqlite3

前端 未结 5 1532
梦谈多话
梦谈多话 2020-12-02 14:20

Is there an easy way to copy an existing table structure to a new one? (dont need the data, only the structure -> like id INTEGER, name varchar(20) ...)

Thx

5条回答
  •  感动是毒
    2020-12-02 15:08

    I would prefer :

    > sqlite3 
    
    sqlite3 > .output 
    sqlite3 > .dump 
    

    The line above generates the dump of table that includes DDL and DML statement.

    Make changes in this file, i.e. find and replace the table name with new table name

    Also, replace "CREATE TRIGGER " with "CREATE TRIGGER _" , this will replace existing triggers with trigger names with a new table name on it. That will make it unique and will not cause conflicts with existing triggers. Once all schema changes are implemented, read it back into database using .read

    sqlite3 > .read output_file
    

    This can be scripted in shell file using shell commands like :

    echo ".dump " | sqlite3  > 
    sed -i.bak "s/\b\b//g" 
    sed -i.bak "s/\bCREATE TRIGGER \b/CREATE TRIGGER /g" 
    echo ".read " | sqlite3 
    rm .bak 
    
    
    

    For example :

    If you have table T and new table is TClone in db file D with file F to be created : then

    echo ".dump T" | sqlite3 D.sqlite > F
    sed -i.bak "s/\bT\b/TClone/g" F
    sed -i.bak "s/\bCREATE TRIGGER \b/CREATE TRIGGER TClone_>/g" F
    echo ".read F" | sqlite3 D.sqlite 
    rm T.bak
    

    Finally, you can generalize this script by creating a parameterized version where you can pass source_table, destination_table , db_file as parameters that can be used to clone any table.

    I tested this and it works.

    Testing :

    sqlite3 
    sqlite3 > select * from ;
    

    should give you same results as original table. and

    sqlite3 > .schema 
    

    should have same schema as that of original table with a new name.

    提交回复
    热议问题