I\'m wondering if there is any way in mysqldump to add the appropriate create table option [IF NOT EXISTS]. Any ideas?
To Find and replace the text On Windows 7 Using PowerShell
Open command prompt and use the command below
powershell -Command "(gc E:\map\map_2017.sql) -replace 'CREATE TABLE', 'CREATE TABLE IF NOT EXISTS' | Out-File E:\map\map_replaced.sql"
First param is the filepath
Second param is 'find string'
Third param is 'replace string'
This command will create a new file with the replaced text. Remove the Command starting from '|' (pipe) if you want to replace and save contents on the same file.
The dump output is the combination of DROP and CREATE, so you must remove DROP statement and change the CREATE statement to form a valid (logical) output:
mysqldump --no-data -u root <schema> | sed 's/^CREATE TABLE /CREATE TABLE IF NOT EXISTS /'| sed 's/^DROP TABLE IF EXISTS /-- DROP TABLE IF EXISTS /' > <schema>.sql
Using sed
as described by @Pawel works well. Nevertheless you might not like the idea of piping your data through more potential error sources than absolutely necessary. In this case one may use two separate dumps:
--no-data --skip-add-drop-table
)--no-create-info --skip-add-drop-table
) There are some other things to take care of though (e.g. triggers). Check the manual for details.
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
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
.
The sed will be much faster without the 'g' (global) at its end:
eg:
mysqldump -e <database> | sed 's/^CREATE TABLE /CREATE TABLE IF NOT EXISTS /' > <database>.sql