Error declaring integer variable inside MySQL stored function

Paul Freeman-Powell picture Paul Freeman-Powell · Aug 1, 2012 · Viewed 34.8k times · Source

I'm getting an error when trying to declare a new stored function in MySQL (Server version: 5.5.13)

Basically, I have a large table which classifies strings depending on how they start. My function takes a string (from user input) and then tells you the classification of that string by searching the database for the classification. It's a bit like a LIKE query, except in reverse as it's the user input that contains the full string and the database contains the string being searched for. Hope that makes sense!

The concept and logic behind it work fine as I've written/developed this in PHP and it works beautifully, however when trying to translate this into a stored function I'm getting an error from MySQL. The code of the function is:

delimiter $

DROP FUNCTION IF EXISTS get_string_class$
CREATE FUNCTION get_string_class(mystring VARCHAR(15))

RETURNS VARCHAR(15)
READS SQL DATA
BEGIN

DECLARE i INT;
SET i = 2;

DECLARE mystringlength INT;
SET mystringlength = LENGTH(mystring);

DECLARE segment VARCHAR(15);
DECLARE String_Class VARCHAR(15);
SET String_Class = NULL;

WHILE i <= mystringlength DO

   SET segment = LEFT(mystring, i);

   SET String_Class = (SELECT String_Class FROM string_class_list WHERE String_Begins = segment);

   IF SELECT FOUND_ROWS() = 1 THEN
      RETURN String_Class
   END IF;

   i = i + 1;

END WHILE;

RETURN String_Class;

END$
delimiter ;

I'm getting this error:

#1064 - You have an error in your SQL syntax; check the manual that corresponds 
to your MySQL server version for the right syntax to use near 
'DECLARE mystringlength INT; SET mystringlength = LENGTH(mystring);
DECLARE segm' at line 10 

I've done lots of playing around to trying and work out where I'm going wrong. I've even stripped out the loop altogether to test it, but still get the same error. Does anyone know what I've done wrong where declaring that INT variable? It's probably something incredibly basic...!

Thanks very much in advance.

Answer

Devart picture Devart · Aug 1, 2012

There were some syntax errors -

One of them is - all declarations must be at the begining of the BEGIN...END clause.

DELIMITER $

DROP FUNCTION IF EXISTS get_string_class$
CREATE FUNCTION get_string_class(mystring VARCHAR(15))

RETURNS VARCHAR(15)
READS SQL DATA
BEGIN

DECLARE i INT;
DECLARE segment VARCHAR(15);
DECLARE String_Class VARCHAR(15);
DECLARE mystringlength INT;

SET i = 2;
SET mystringlength = LENGTH(mystring);
SET String_Class = NULL;

WHILE i <= mystringlength DO

   SET segment = LEFT(mystring, i);

   SET String_Class = (SELECT String_Class FROM string_class_list WHERE String_Begins = segment);

   IF (SELECT FOUND_ROWS()) = 1 THEN
      RETURN String_Class;
   END IF;

   SET i = i + 1;

END WHILE;

RETURN String_Class;

END$
DELIMITER ;