Thursday, October 4, 2007

MySql stored proc delimiters

When creating a stored proc in MySQL (MySQL 5.0+ supports this), unfortunatly you have to workaround delimiter issues. If you just use semicolons to terminate each line as you would in MS SQL Server, it won't work. So, I'm posting a template here to help developers. I'll use $$ as the delimitor, but you can use a different symbol if you like:

DELIMITER $$;
DROP PROCEDURE IF EXISTS `my_db`.`my_proc_name`$$
CREATE PROCEDURE `my_db`.`my_proc_name` ()
BEGIN
declare my_var_A INT;
[some more statements, each terminated by ; ... ];
END$$
DELIMITER ;$$

The first line configures your new symbol ($$) to be statement terminator. This allows us to put semicolons, the ordinary statement termintor inside our stored procedure, without MySQL trying to go ahead and start executing them as statements when we run the above script to create the stored procedure. See the line "END$$". We terminate that with our new "real" delimiter to allow MySQL to execute that block, thereby creating the whole stored procedure. Then we restore the delimiter to semicolon. Now when we execute our stored procedure, we should be using the default semicolon delimiter, and so the stored procedure will run fine, having ordinary statement terminators.

No comments: