Exit MySQL script if database exists

两盒软妹~` 提交于 2019-12-14 01:30:04

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!