Stephane B. Stephane B. - 1 month ago 8
SQL Question

SQL error syntax 1064

I have a syntax error that I have been trying to fix but I can't figure it out. Error tells that there is a problem near

'SET result = CONCAT(result,charac); END IF; SET indexchar = indexchar+1;'


Full function I am trying to create:

DELIMITER //
DROP FUNCTION IF EXISTS `alphabet`;
CREATE FUNCTION `alphabet` (serial_number CHAR, name VARCHAR(100)) RETURNS VARCHAR(50)
DETERMINISTIC
BEGIN
DECLARE result VARCHAR(40) DEFAULT '';
DECLARE stringalpha VARCHAR(50) DEFAULT 'abcdefghijklmnopqrstuvwxyz0123456789';
DECLARE indexchar int DEFAULT 1;
DECLARE charlength INT;
DECLARE charac CHAR(1);

SET charlength = CHAR_LENGTH(stringalpha);

WHILE indexchar <= charlength DO
SET charac = SUBSTRING(stringalpha,indexchar,1);
IF (serial_number LIKE CONCAT('%',charac,'%') OR name LIKE CONCAT('%',charac,'%'))
SET result = CONCAT(result,charac);
END IF;
SET indexchar = indexchar+1;
END WHILE

RETURN result;
END //
DELIMITER ;


I have tried to write without success:

SET result = CONCAT('result','charac');

Answer
DROP FUNCTION IF EXISTS `alphabet`;
DELIMITER //
CREATE FUNCTION `alphabet` (serial_number CHAR, name VARCHAR(100)) RETURNS VARCHAR(50) 
DETERMINISTIC
BEGIN
    DECLARE result VARCHAR(40) DEFAULT '';
    DECLARE stringalpha VARCHAR(50) DEFAULT 'abcdefghijklmnopqrstuvwxyz0123456789';
    DECLARE indexchar int DEFAULT 1;
    DECLARE charlength INT;
    DECLARE charac CHAR(1);

    SET charlength = CHAR_LENGTH(stringalpha);

WHILE indexchar <= charlength DO
    SET charac = SUBSTRING(stringalpha,indexchar,1);
    IF (serial_number LIKE CONCAT('%',charac,'%') OR name LIKE CONCAT('%',charac,'%')) THEN
        SET result = CONCAT(result,charac);
    END IF;
    SET indexchar = indexchar+1;
END WHILE; -- ********************** missing semi

RETURN result;
END //
DELIMITER ;

missing THEN, missing semi-colon after END WHILE, delimiter at the top was on the wrong line