1

I have a SQL script in docker, but I only want to run the script if it has not been run before. So, I though I would have something like:

IF dbname EXISTS
THEN
    exit;
END IF;

Looking around I managed to find code that will return 0 or 1 if the database exists:

SELECT IF(EXISTS(SELECT SCHEMA_NAME 
    FROM INFORMATION_SCHEMA.SCHEMATA 
    WHERE SCHEMA_NAME = 'mysql'),true,false);

but I cannot figure out how to turn this into an exit statement

IF(EXISTS (SELECT SCHEMA_NAME FROM INFORMATION_SCHEMA.SCHEMATA WHERE SCHEMA_NAME = 'mysql')
THEN
    exit;
END IF;

gives multiple syntax errors.

I am working with CentOS 6.7 and MySQL server 5.1.73 (forgot it is not MariaDB until CentOS 7)

1

3 Answers 3

1

What do you mean? Does the script create anything? If yes you could use this trick:

IF SELECT SCHEMA_NAME FROM INFORMATION_SCHEMA.SCHEMATA 
WHERE SCHEMA_NAME = 'demo-database' then

  CREATE DATABASE `demo-database`
  // do other stuff ect

ENDIF

That might work. Atleast for me it did ;)

Sign up to request clarification or add additional context in comments.

2 Comments

my SQL script creates the database and inserts data. It is almost 8000 lines, so I do not want to put the whole thing into an if statement.
This is the source of my confusion. If I enter your code in mysql interactive I get: ERROR 1064 (42000): You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'IF SELECT SCHEMA_NAME FROM INFORMATION_SCHEMA.SCHEMATA WHERE SCHEMA_NAME = 'dem' at line 1
0

After further thought and research, I think this is a limitation of the MySQL console. I was treating my SQL "script" as a script where it is actually just a list of commands. The IF statement in MySQL really designed to be part of a SELECT statement. So, I make this decision to run the SQL commands within a bash script.

Comments

0

Rather than causing a certain action if the script exists, have your original action occur only if the script does NOT exist, such as

CREATE DATABASE IF NOT EXISTS DBName;
///all the rest of your SQL, 

This means the SQL will only run if the data structure is not already there. This looks like what you're wanting.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.