MySQL IF…ELSE statement can only be used inside stored procedure. They will not work in regular scope. The syntax is
DELIMITER // CREATE PROCEDURE IfTest() BEGIN if(@test = 2) then begin select 'I know you'; end; else begin select 'I dont know you'; end; end if; END // DELIMITER ;
If you run the stored procedure by calling call IfTest();, it should print
call IfTest(); --output I know you
Notice that the IF command will not work if you run the if block outside the stored procedure.
General Syntax for IF…THEN…ELSE command is
IF(condition) THEN BEGIN (your statements;) END; END IF;
- Make sure you are running if IF…THEN…ELSE block inside stored procedure. It will not work outside stored procedure.
- Make sue you are writing ; at the end of each statement
- Do not forget the THEN statement
- Do no forget the END; and END IF; statement at the end
- It is good practice to create stored procedure using command line.