MySQL statements conditional execution

Creating a MySQL script to populate some tables with data for tests. Want to avoid to execute the script multiple times (not only me in the team :). Since I don't own the tables I can not create constrains or delete table content.

Rough code idea of what I want to do:

IF (SELECT EXISTS(SELECT * FROM <1st_Table> WHERE <1st_Record_Inserted>)) GOTO DontDoAnythingLabel

INSERT <1st_Table> ...
INSERT <2nd_Table> ...
INSERT <3rd_Table> ...
...
UPDATE <N_Table>
...
INSERT <M_Table> ...

DontDoAnythingLabel:

How can I write this code with MySQL?

Upvotes: 0

Views: 136

Answers (1)

user4489658
user4489658

Reputation:

If you're using Linux/Unix then you can use a script like this:

#!/bin/bash
res=`mysql -s -r -N -u [user] -p[password] -e 'SELECT EXISTS (SELECT * FROM <1st_Table> WHERE <1st_Record_Inserted>)' [database]`
if [ $res = "1" ]; then
    mysql -u [user] -p[password] [database] < sql_script.sql;
else
    echo "There are no such records!";
fi
mysql -u [user] -p[password] [database] < next_sql_script.sql;

Otherwise create something like this with Windows cmd/VBscript/whatever.

Upvotes: 1

Related Questions