MySQL - Trouble with creating user defined function (UDF) - mysql

I'm trying to create this function:
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
But MySQL says:
13:52:45 [CREATE - 0 row(s), 0.000 secs] [Error Code: 1064, SQL State: 42000] 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 '' at line 5
What could I being wrong? The syntax looks correct to me.

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 ;
In MySQL Command-Line Client (and many other SQL clients) 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

Related

MySQL said: #1338 - Cursor declaration after handler declaration

I'm on developing web project and i get some problem with migration from oracle database to mysql database. I want to create function with this code :
DROP FUNCTION IF EXISTS F_MANIFEST_GABUNG_SMR;
DELIMITER //
CREATE FUNCTION F_MANIFEST_GABUNG_SMR (input_val varchar(4000))
RETURNS VARCHAR(4000)
BEGIN
DECLARE return_text VARCHAR(10000) DEFAULT NULL;
DECLARE not_found INT DEFAULT 0;
DECLARE CONTINUE HANDLER FOR NOT FOUND SET not_found = 1;
DECLARE x CURSOR FOR SELECT DISTINCT IFNULL(SMR,'-') SMR FROM MANIFEST_EDI_SMR WHERE BL_NBR = input_val; OPEN x;
FETCH x INTO;
WHILE NOT_FOUND=0
DO
SET return_text = concat(ifnull(return_text, '') , ' ' , IFNULL(x.SMR, '')) ;
FETCH INTO;
END WHILE;
CLOSE ;
IF char_length(return_text) > 85 THEN
SET return_text = concat(ifnull(substr(return_text,1,85), '') , ' detail asp BL');
END IF;
RETURN return_text;
END;
//
DELIMITER ;
I am using phpmyadmin to store function with routine. Thanks for your help :)
The error message is self explanatory:you have declare the cursor after handler,need to change the order:
DROP FUNCTION IF EXISTS F_MANIFEST_GABUNG_SMR;
DELIMITER //
CREATE FUNCTION F_MANIFEST_GABUNG_SMR (input_val varchar(4000))
RETURNS VARCHAR(4000)
BEGIN
DECLARE return_text VARCHAR(10000) DEFAULT NULL;
DECLARE not_found INT DEFAULT 0;
-- Declare cursor before handler
DECLARE x CURSOR FOR SELECT DISTINCT IFNULL(SMR,'-') SMR
FROM MANIFEST_EDI_SMR WHERE BL_NBR = input_val; OPEN x;
-- handler need to be after cursor
DECLARE CONTINUE HANDLER FOR NOT FOUND SET not_found = 1;
FETCH x INTO;
WHILE NOT_FOUND=0
DO
SET return_text = concat(ifnull(return_text, '') , ' ' , IFNULL(x.SMR, '')) ;
FETCH INTO;
END WHILE;
CLOSE ;
IF char_length(return_text) > 85 THEN
SET return_text = concat(ifnull(substr(return_text,1,85), '') , ' detail asp BL');
END IF;
RETURN return_text;
END;
//
DELIMITER ;
More details can be found at:https://dev.mysql.com/doc/refman/8.0/en/cursors.html

What's wrong w/ MySql Statement (Function)

I'm using MySql57
What's wrong with this script?(I'm Mysql newbie)
Error Code: 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 '= 'A0001'; ELSE BEGIN gubun1 = LEFT(cur_max,0,1); gu' at line 10
DELIMITER $$
CREATE FUNCTION narae.FN_GET_GUBUN_MAX() RETURNS varchar(100)
BEGIN
DECLARE cur_max varchar(100);
DECLARE gubun1 varchar(1);
DECLARE gubun2 varchar(100);
DECLARE RTN_VAL varchar(100);
SELECT IFNULL(MAX(gubun_code),'A0001') INTO cur_max from gubun_code;
IF cur_max = 'A0001' THEN RTN_VAL = 'A0001';
ELSE
BEGIN
gubun1 = LEFT(cur_max,0,1);
gubun2 =
LPAD(CONVERT(CONVERT(RIGHT(cur_max,4),UNSIGNED)+1,CHAR),4,'0');
RTN_VAL = CONCAT(gubun1,gubun2);
END
RETURN RTN_VAL;
END $$
DELIMITER ;
There are several errors in the function. I think this might work:
DELIMITER $$
CREATE FUNCTION narae.FN_GET_GUBUN_MAX() RETURNS varchar(100)
BEGIN
DECLARE v_cur_max varchar(100);
DECLARE v_RTN_VAL varchar(100);
SELECT COALESCE(MAX(gubun_code), 'A0001')
INTO v_cur_max
FROM gubun_code;
IF cur_max = 'A0001' THEN
SET v_RTN_VAL = 'A0001';
ELSE
SET v_RTN_VAL = CONCAT(LEFT(cur_max, 1), RIGHT(cur_max, 4) + 1);
END IF;
RETURN v_RTN_VAL;
END $$
DELIMITER ;
I would further simplify this by doing all the logic in the SQL statement, but this seems to be in the spirit of your solution.

select only digits, numbers from text

I have a field text, In it there is information about such
sch hcbhsc hscbshcbc xxxxxxxx sgxfag jdhajdh;
dchbdbc bdcbdh bchdbd xx/xx-xxxx/xx svdhs sbjbsc
bdchbdc jncjdnc jbcjb xx/xx-xxxxx/xx gcvsgc jcbjsb
dchjbd bhjcbdcb bdcbcd xx-xxxx/xx shchscv hscbhsc
dhcbhd jdcbjdb jdcnjdcn xx-xxxxx/xx shcvsch jbscjc
Place x is only a digit, I need to write select and only those numbers are taken
Use SUBSTRING and PATINDEX string functions IN SQL server :
SELECT SUBSTRING(Your_FieldName, PATINDEX('%[0-9]%', Your_FieldName),
LEN(Your_FieldName))
For MYSQL refer below URL :
Query to get only numbers from a string
string
There is no formal PATINDEX() function in MySQL that achieves both the regex pattern lookup with returned character index, define User-Defined function that loops through each character in the length of a string and checks a REGEXP pattern on the character. Once created, use such a function in-line of a query.
DROP FUNCTION IF EXISTS PatIndex;
DELIMITER $$
CREATE FUNCTION PatIndex(pattern VARCHAR(255), tblString VARCHAR(255)) RETURNS INTEGER
DETERMINISTIC
BEGIN
DECLARE i INTEGER;
SET i = 1;
myloop: WHILE (i <= LENGTH(tblString)) DO
IF SUBSTRING(tblString, i, 1) REGEXP pattern THEN
RETURN(i);
LEAVE myloop;
END IF;
SET i = i + 1;
END WHILE;
RETURN(0);
END
Here is a MySQL function (routine) that will do just that. It is an improved version from the solution given here: how-to-get-only-digits-from-string-in-mysql
This improved version can handle much larger numbers. The old solution was limited by the INTEGER value, so if you had phone numbers for example (or string containing many digits), it would fail with out of range for column.
DELIMITER $$
CREATE FUNCTION ExtractNumber (in_string VARCHAR(50))
RETURNS varchar(50)
NO SQL
BEGIN
DECLARE ctrNumber VARCHAR(50);
DECLARE finNumber VARCHAR(50) DEFAULT '';
DECLARE sChar VARCHAR(1);
DECLARE inti VARCHAR(50) DEFAULT 1;
IF LENGTH(in_string) > 0 THEN
WHILE(inti <= LENGTH(in_string)) DO
SET sChar = SUBSTRING(in_string, inti, 1);
SET ctrNumber = FIND_IN_SET(sChar, '0,1,2,3,4,5,6,7,8,9');
IF ctrNumber > 0 THEN
SET finNumber = CONCAT(finNumber, sChar);
END IF;
SET inti = inti + 1;
END WHILE;
RETURN CAST(finNumber AS UNSIGNED);
ELSE
RETURN 0;
END IF;
END$$
DELIMITER ;
Now you can do this:
SELECT ExtractNumber(my_field)
FROM my_table;

What's wrong with this MYSQL query?

delimiter |
CREATE FUNCTION BASE64_DECODE (input BLOB)
RETURNS BLOB
CONTAINS SQL
DETERMINISTIC
SQL SECURITY INVOKER
BEGIN
DECLARE ret BLOB DEFAULT '';
DECLARE done TINYINT DEFAULT 0;
IF input IS NULL THEN
RETURN NULL;
END IF;
each_block:
WHILE NOT done DO BEGIN
DECLARE accum_value BIGINT UNSIGNED DEFAULT 0;
DECLARE in_count TINYINT DEFAULT 0;
DECLARE out_count TINYINT DEFAULT 3;
each_input_char:
WHILE in_count < 4 DO BEGIN
DECLARE first_char CHAR(1);
IF LENGTH(input) = 0 THEN
RETURN ret;
END IF;
SET first_char = SUBSTRING(input,1,1);
SET input = SUBSTRING(input,2);
BEGIN
DECLARE tempval TINYINT UNSIGNED;
DECLARE error TINYINT DEFAULT 0;
DECLARE base64_getval CURSOR FOR SELECT val FROM base64_data WHERE c = first_char;
DECLARE CONTINUE HANDLER FOR SQLSTATE '02000' SET error = 1;
OPEN base64_getval;
FETCH base64_getval INTO tempval;
CLOSE base64_getval;
IF error THEN
ITERATE each_input_char;
END IF;
SET accum_value = (accum_value << 6) + tempval;
END;
SET in_count = in_count + 1;
IF first_char = '=' THEN
SET done = 1;
SET out_count = out_count – 1;
END IF;
END; END WHILE;
WHILE out_count > 0 DO BEGIN
SET ret = CONCAT(ret,CHAR((accum_value & 0xff0000) >> 16));
SET out_count = out_count – 1;
SET accum_value = (accum_value << 8) & 0xffffff;
END; END WHILE;
END; END WHILE;
RETURN ret;
END |
The error I'm getting is:
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 '– 1;
END IF;
END; END WHILE;
' at line 52
WHILE loops in MySQL are simply terminated with END WHILE;. You've got END; END WHILE; which is incorrect.
That END before END WHILE; is causing the problem. You already have an END on line 46, so this one is trying to end the function. I'll bet you can just remove it.
The problem, silly as it was, was the use of non-standard symbols throughout. -s and 's were wrong format. Due to the encoding of the IDE I am using or something just as silly.
facepalm

Unable to create UDF in my sql

Unable to create UDF. Am getting below error at the time of creation
Error: 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 ';
CREATE FUNCTION `seat_count`(seatno varchar(250))
RETURNs varchar(250)
BEG' at line 1
code: http://pastebin.com/uf4DkXZh
code:
CREATE FUNCTION `seat_count`(seatno VARCHAR(250))
RETURNS VARCHAR(250)
BEGIN
SET #str= REPLACE(seatno, ',', '');
SET #stcnt=CHAR_LENGTH(str);
SET #x=1;
SET #result;
WHILE (#x <= #stcnt)
DO
SET #st=SUBSTRING_INDEX(#str,',',X);
IF ((LENGTH(#seatno) - LENGTH(REPLACE(#seatno, st, '')))/LENGTH(#st)=1)
THEN SET #result=CONCAT(#st,#result);
END IF;
SET #x=#x+1;
END WHILE;
RETURN #result;
END$$
When you develop a stored procedure in MySQL, you can pass the input parameters and declare the local variables, the local variable are not prepended with any prefixes unlike user-defined variable which are prepended with #. For detail procedure vs user-defined variable
DELIMITER $$
CREATE FUNCTION `SEAT_COUNT`(`seatno` VARCHAR(250)) RETURNS VARCHAR(250)
DETERMINISTIC
BEGIN
DECLARE result VARCHAR(250);
SET #str = REPLACE(seatno, ',', '');
SET #stcnt = CHAR_LENGTH(#str);
SET #x = 1;
WHILE (#x <= #stcnt)
DO
SET #st = SUBSTRING_INDEX(#str,',',X);
IF ((LENGTH(#seatno) - LENGTH(REPLACE(#seatno, st, '')))/LENGTH(#st)=1)
THEN SET result = CONCAT(#st, #result);
END IF;
SET #x = #x+1;
END WHILE;
RETURN result;
END$$
DELIMITER ;
You have defined the result variable as user-defined e.g SET #result instead of local variable e.g DECLARE result VARCHAR(250)
I hope this will work at your end too.