MySQL: How do I use delimiters in triggers?

Part 1

The delimiters are used for source objects like stored procedure/function, trigger or event. All these objects may have a body – code within BEGIN…END clause.

All statement in MySQL scripts should be ended with delimiter, the default is ‘;’. But what to do if source object has body with some statements, e,g:

INSERT INTO table1 VALUES(1);

CREATE PROCEDURE procedure1()
BEGIN
  SET @s="SELECT SQRT(POW(?,2) + POW(?,2)) AS hypotenuse";
  PREPARE stmt2 FROM @s;
  SET @a = 6;
  SET @b = 8;
  EXECUTE stmt2 USING @a, @b;
END;

INSERT INTO table1 VALUES(2);

How many statemants? 3 or 8? The answer is three, because script has two INSERTs and one CREATE PROCEDURE statements. As you see, CREATE PROCEDURE has some internal statements too; we should say to MySQL client that all these statement (inside BEGIN…END) – are part of ONE statement; we can do it with a help of delimiters:

INSERT INTO table1 VALUES(1);

DELIMITER $$

CREATE PROCEDURE procedure1()
BEGIN
  SET @s="SELECT SQRT(POW(?,2) + POW(?,2)) AS hypotenuse";
  PREPARE stmt2 FROM @s;
  SET @a = 6;
  SET @b = 8;
  EXECUTE stmt2 USING @a, @b;
END$$

DELIMITER ;

INSERT INTO table1 VALUES(2);

Note, when your trigger has no BEGIN…END clause, delimiters may be omitted.


Part 2

Without delimiters the statement will be parsed as –

CREATE PROCEDURE procedure1()
BEGIN
  SET @s="SELECT SQRT(POW(?,2) + POW(?,2)) AS hypotenuse";

instead of –

CREATE PROCEDURE procedure1()
BEGIN
  SET @s="SELECT SQRT(POW(?,2) + POW(?,2)) AS hypotenuse";
  PREPARE stmt2 FROM @s;
  SET @a = 6;
  SET @b = 8;
  EXECUTE stmt2 USING @a, @b;
END

Leave a Comment