MySQL - Trouble with creating user defined function (UDF)

时光毁灭记忆、已成空白 提交于 2019-12-02 03:57:22

You have to change the delimiter so you can use ; inside the function:

DELIMITER $$

CREATE FUNCTION remove_non_alphanum (prm_strInput varchar(3000))
RETURNS VARCHAR(3000)
DETERMINISTIC
BEGIN
  DECLARE i INT DEFAULT 1;
  DECLARE v_char VARCHAR(1);
  DECLARE v_parseStr VARCHAR(3000) DEFAULT '';
WHILE (i <= LENGTH(prm_strInput) )  DO
  SET v_char = SUBSTR(prm_strInput,i,1);
  IF v_char REGEXP '^[A-Za-z0-9]$' THEN
        SET v_parseStr = CONCAT(v_parseStr,v_char);  
  END IF;
  SET i = i + 1;
END WHILE;
RETURN trim(v_parseStr);
END
$$

DELIMITER ;

Update: In MySQL, the default delimiter is ;. So, when you type your original code, MySQL thinks the first command ends where the first ; is found (at line 5, as the error message states), thus you get an error because this is not valid SQL:

CREATE FUNCTION remove_non_alphanum (prm_strInput varchar(3000))
RETURNS VARCHAR(3000)
DETERMINISTIC
BEGIN
  DECLARE i INT DEFAULT 1;

If you change the delimiter to anything else, MySQL identifies the complete command (from CREATE FUNCTION to END and runs it. Voilá! Your function is created. Finally, when you run your function, the code runs just fine because the function body is composed of several statements using the default delimiter.

I found the answer here.

I turns out it was some weird DB Visualizer issue.

Enclosing the complete block in "--/" and "/" worked for me:

--/
CREATE FUNCTION remove_non_alphanum (prm_strInput varchar(3000))
RETURNS VARCHAR(3000)
DETERMINISTIC
BEGIN
  DECLARE i INT DEFAULT 1;
  DECLARE v_char VARCHAR(1);
  DECLARE v_parseStr VARCHAR(3000) DEFAULT '';
WHILE (i <= LENGTH(prm_strInput) )  DO
  SET v_char = SUBSTR(prm_strInput,i,1);
  IF v_char REGEXP '^[A-Za-z0-9]$' THEN
        SET v_parseStr = CONCAT(v_parseStr,v_char);  
  END IF;
  SET i = i + 1;
END WHILE;
RETURN trim(v_parseStr);
END
/

An alternative to

--/
CREATE FUNCTION ... 
/ 

is:

@delimiter $$;
CREATE FUNCTION ...
@delimiter ;$$

More info: http://www.dbvis.com/doc/main/doc/ug/sqlCommander/sqlCommander.html#mozTocId437790

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!