0

I'm trying to create a mySQL Script file, so i can easily execute my changes in differente databases, but I'm having problems with a IF statement. (I'm using MySQL Workbench).

CREATE TABLE IF NOT EXISTS `build` (
    `ID` int(11) NOT NULL AUTO_INCREMENT,
    `Version` varchar(20) NOT NULL,
    `Date` datetime DEFAULT NULL,  
    PRIMARY KEY (`ID`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;

IF EXISTS(select 1 from build where Versao = '1.1') THEN select "yes";

The create table sentence is executed correctly, but the "IF Exists(select..." statement is giving the following error:

SYNTAX ERROR: IF (if) is not a valid input at this position

The select "Yes" command will actually be replaced by an insert command. I'm just trying to test if the IF command will work.

I've also tried to put the IF EXISTS(select line in a separated query, but had the same result.

What am I doing wrong?

2 Answers 2

1

The SQL IF function as I imagine you want to use should be used inside a function, which you never declared.

If you want a standalone query which will behave the way you expect, then you can try this:

SELECT CASE WHEN EXISTS (SELECT 1 FROM build WHERE Versao = '1.1')
            THEN "yes"
            ELSE "no"
       END
LIMIT 1
Sign up to request clarification or add additional context in comments.

Comments

0

SQL functions can only be used inside a statement or inside a stored procedure/routine.

This SELECT statement should work for you:

SELECT IF(EXISTS(SELECT 1 FROM build WHERE Versao = '1.1'), 'yes', 'no') AS test;

2 Comments

The problem is that i don't want to return yes or no. It was just a test. what i want is to execute one or more commands depending on the table existing.
OK. Could you please give an example of the commands you'd like to execute conditionally? Are they in SQL?

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.