HiveBrain v1.2.0
Get Started
← Back to all entries
debugsqlMinor

MySQL begin end from documentation doesn't work

Submitted by: @import:stackexchange-dba··
0
Viewed 0 times
documentationmysqldoesnworkendfrombegin

Problem

I am using XAMPP. I simply tired this begin..end -

CREATE PROCEDURE dowhile()
BEGIN
  DECLARE v1 INT DEFAULT 5;
  WHILE v1 > 0 DO
    SET v1 = v1 - 1;
  END WHILE;
END;


statement and got error. This happens with every begin..end or while that I try. Is it because of my mysql version ? XAMPP version is v3.2.2 and mysql is Version information: 4.7.9. I am really confused. The error is :

CREATE PROCEDURE dowhile()
BEGIN
  DECLARE v1 INT DEFAULT 5
MySQL said: Documentation

#1064 - You have an error in your SQL syntax; check the manual that corresponds to your MariaDB server version for the right syntax to use near '' at line 3


Thank you in advance!

Solution

While creating procedure, function or another compound statement consisted from more than 1 command, You MUST use DELIMITER statement.

The reason is simple - command to create procedure is one command. But it consists from a lot of common commands. When You enter its code, server has no any marker, what kind of command is terminated by any delimiter - simple statement or compound statement. To avoid it You must use separate delimiters for that aims. Because standard delimiter will be used when server executes procedure, You must NOT alter default delimiter used for common commands. So You must alter delimiter used for fixed compound statement.

You must update Your code:

DELIMITER @@; -- Alter delimiter to 3-symbol one 
              -- not contained in compound statement we want to create

CREATE PROCEDURE dowhile()
BEGIN
  DECLARE v1 INT DEFAULT 5; -- Std delimiter, terminates single statement
  WHILE v1 > 0 DO
    SET v1 = v1 - 1;
  END WHILE;
END;
@@;  -- Altered delimiter terminated compound statement

DELIMITER ; -- restore delimiter to standard semicolon

Code Snippets

DELIMITER @@; -- Alter delimiter to 3-symbol one 
              -- not contained in compound statement we want to create

CREATE PROCEDURE dowhile()
BEGIN
  DECLARE v1 INT DEFAULT 5; -- Std delimiter, terminates single statement
  WHILE v1 > 0 DO
    SET v1 = v1 - 1;
  END WHILE;
END;
@@;  -- Altered delimiter terminated compound statement

DELIMITER ; -- restore delimiter to standard semicolon

Context

StackExchange Database Administrators Q#207758, answer score: 4

Revisions (0)

No revisions yet.