问题
I have a MySQL script that I want to use only if the database doesn't exist to inject some initial demo data for development. If it does exist I just want to break out of the script. The script starts like
CREATE DATABASE IF NOT EXISTS `demo-database`;
USE `demo-database`;
Is there a way to exit here or above the create database if the database exists so that it wont run through all the table setups and inserts?
回答1:
Try this. Use INFORMATION_SCHEMA.SCHEMATA to check the existence of Database
If not exists (SELECT 1
FROM INFORMATION_SCHEMA.SCHEMATA
WHERE SCHEMA_NAME = 'demo-database')
CREATE DATABASE `demo-database`
.....
回答2:
What I believe now is that the construct with an if/else/endif can only be used in a stored program (see also https://dev.mysql.com/doc/refman/8.0/en/if.html)
I do not have a workaround other than creating a stored procedure that contains the code. In my situation I also have code I would to execute only on a test environment. I am creating only the stored procedure on test then as well.
来源:https://stackoverflow.com/questions/27734205/exit-mysql-script-if-database-exists