MySQL IF ELSE Statement

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;

Caveats:

  1. Make sure you are running if IF…THEN…ELSE block inside stored procedure. It will not work outside stored procedure.
  2. Make sue you are writing ; at the end of each statement
  3. Do not forget the THEN statement
  4. Do no forget the END; and END IF;  statement at the end
  5. It is good practice to create stored procedure using command line.
Advertisements
This entry was posted in Uncategorized. Bookmark the permalink.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s