Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Create table if not exists from mysqldump

I'm wondering if there is any way in mysqldump to add the appropriate create table option [IF NOT EXISTS]. Any ideas?

like image 581
khelll Avatar asked Feb 08 '10 09:02

khelll


People also ask

What does create table if not exists mean in SQL?

The clause “if not exists” is used for the creation of tables and is very useful for avoiding the error “table already exists”, as it will not create a table if, in the database, any table is already available by the name of the new table.

Which command creates a database only if it does not already exist?

The IF NOT EXISTS clause prevents you from an error of creating a new database that already exists in the database server. You cannot have 2 databases with the same name in a MySQL database server.

What is single transaction in Mysqldump?

Mysqldump with Transactions The --single-transaction flag will start a transaction before running. Rather than lock the entire database, this will let mysqldump read the database in the current state at the time of the transaction, making for a consistent data dump.


2 Answers

Try to use this on your SQL file:

sed 's/CREATE TABLE/CREATE TABLE IF NOT EXISTS/g' <file-path> 

or to save

sed -i 's/CREATE TABLE/CREATE TABLE IF NOT EXISTS/g' <file-path> 

it's not ideal but it works :P

like image 81
Pawel Avatar answered Sep 18 '22 12:09

Pawel


According to one source, mysqldump does not feature this option.

You could use the --force option when importing the dump file back, where MySQL will ignore the errors generated from attempts to create duplicate tables. However note that with this method, other errors would be ignored as well.

Otherwise, you can run your dump file through a script that would replace all occurrences of CREATE TABLE with CREATE TABLE IF NOT EXISTS.

like image 30
Daniel Vassallo Avatar answered Sep 22 '22 12:09

Daniel Vassallo