Error in while in mysql - mysql

I want to create function in mysql for :
Input: 7589586586 Output: (758) 958-6586
Input: 758ABC6586 Output: (758) 222-6586
Input: 758ABC65 Output: Invalid Formats (like mobile keypad)
The following mysql code gives errors:
DELIMITER $$
CREATE FUNCTION fn_bhagyashreed_phonenumber(input varchar(20))
RETURNS varchar(50)
LANGUAGE SQL
BEGIN
DECLARE compare varchar(30) ;
DECLARE cnt INT;
DECLARE varout varchar(30);
DECLARE val varchar(30);
DECLARE Phoutput varchar(50);
DECLARE var INT;
set var=LENGTH(input);
SET compare ='';
SET cnt =1;
SET varout ='';
SET val = '';
SET Phoutput ='';
if((var<>10)||(input NOT REGEXP '^[[:alnum:]]+$' )) THEN
set Phoutput='Invalid Format';
else if((LENGTH(input))=10) THEN
begin
IF (input REGEXP '^[[:alnum:]]+$' ) THEN
begin
while (cnt<=10) DO
set compare=substring(input,cnt,1);
if compare in('a','b','c','2') THEN
set val=2;
else if compare in('d','e','f','3') THEN
set val=3;
else if compare in('g','h','i','4') THEN
set val=4;
else if compare in('j','k','l','5') THEN
set val=5;
else if compare in('m','n','o','6') THEN
set val=6;
else if compare in('p','q','r','s','7') THEN
set val=7;
else if compare in('t','u','v','8') THEN
set val=8;
else if compare in('w','x','y','z','9') THEN
set val=9;
else if (compare ='1') THEN
set val=1;
else if(compare ='0') THEN
set val=0;
end if;
set varout = CONCAT(varout,val);
set cnt=cnt+1;
end while;
set Phoutput = CONCAT('(',SUBSTR(varout,1,3),')',' ',SUBSTR(varout,4,3),'-',SUBSTR(varout,7,4));
end IF;
end if;
return Phoutput;
end;
$$
DELIMITER ;
The 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 'while; set Phoutput = CONCAT('(',SUBSTR(varout,1,3),')','
',SUBSTR(varout,4,' at line 65

Issues with syntax in your code:
There is no ELSE IF instead there is ELSEIF
You twice opened BEGIN ... END block but never terminated it. In fact you there was no need in using them at all.
A syntactically correct and bit streamlined version of your function might look like this
DELIMITER $$
CREATE FUNCTION fn_bhagyashreed_phonenumber(input VARCHAR(20))
RETURNS VARCHAR(50)
BEGIN
DECLARE compare VARCHAR(30) DEFAULT '';
DECLARE cnt INT DEFAULT 1;
DECLARE varout VARCHAR(30) DEFAULT '';
DECLARE val VARCHAR(30) DEFAULT '';
DECLARE Phoutput VARCHAR(50) DEFAULT '';
DECLARE var INT;
SET var = LENGTH(input);
IF var <> 10 OR input NOT REGEXP '^[[:alnum:]]+$' THEN
SET Phoutput = 'Invalid Format';
ELSE
WHILE cnt <= 10 DO
SET compare = SUBSTRING(input, cnt, 1);
IF compare IN('a','b','c','2') THEN
SET val=2;
ELSEIF compare IN('d','e','f','3') THEN
SET val=3;
ELSEIF compare IN('g','h','i','4') THEN
SET val=4;
ELSEIF compare IN('j','k','l','5') THEN
SET val=5;
ELSEIF compare IN('m','n','o','6') THEN
SET val=6;
ELSEIF compare IN('p','q','r','s','7') THEN
SET val=7;
ELSEIF compare IN('t','u','v','8') THEN
SET val=8;
ELSEIF compare IN('w','x','y','z','9') THEN
SET val=9;
ELSEIF compare = '1' THEN
SET val=1;
ELSEIF compare = '0' THEN
SET val=0;
END IF;
SET varout = CONCAT(varout,val);
SET cnt = cnt + 1;
END WHILE;
SET Phoutput = CONCAT('(',SUBSTR(varout,1,3),')',' ',SUBSTR(varout,4,3),'-',SUBSTR(varout,7,4));
END IF;
RETURN Phoutput;
END$$
DELIMITER ;
Let's try it out:
SELECT fn_bhagyashreed_phonenumber(value) phone
FROM
(
SELECT '7589586586' value UNION ALL
SELECT '758ABC6586' UNION ALL
SELECT '758ABC65'
) q
Output:
| PHONE |
|----------------|
| (758) 958-6586 |
| (758) 222-6586 |
| Invalid Format |
Here is SQLFiddle demo

Cleaned up your code SIGNIFICANTLY:
DELIMITER $$
CREATE FUNCTION fn_phone_number(input VARCHAR(20)) RETURNS VARCHAR(14) LANGUAGE SQL
BEGIN
DECLARE cnt INT;
DECLARE chr CHAR(1);
DECLARE number VARCHAR(10);
SET cnt = 1;
SET number = '';
IF ((LENGTH(input) = 10) && (input REGEXP '^[[:alnum:]]+$')) THEN
WHILE (cnt <= 10) DO
SET chr = SUBSTR(input,cnt,1);
IF chr IN('a','b','c','2') THEN
SET number = CONCAT(number,'2');
ELSEIF chr IN('d','e','f','3') THEN
SET number = CONCAT(number,'3');
ELSEIF chr IN('g','h','i','4') THEN
SET number = CONCAT(number,'4');
ELSEIF chr IN('j','k','l','5') THEN
SET number = CONCAT(number,'5');
ELSEIF chr IN('m','n','o','6') THEN
SET number = CONCAT(number,'6');
ELSEIF chr IN('p','q','r','s','7') THEN
SET number = CONCAT(number,'7');
ELSEIF chr IN('t','u','v','8') THEN
SET number = CONCAT(number,'8');
ELSEIF chr IN('w','x','y','z','9') THEN
SET number = CONCAT(number,'9');
ELSEIF chr IN('0','1') THEN
SET number = CONCAT(number,chr);
END IF;
SET cnt = cnt + 1;
END WHILE;
RETURN CONCAT('(', SUBSTR(number,1,3), ') ', SUBSTR(number,4,3), '-', SUBSTR(number,7,4));
ELSE
RETURN 'Invalid Format';
END IF;
END$$
DELIMITER ;

Related

How to remove Vietnamese Character in MySQL

My Code MYSQL
DELIMITER //
CREATE FUNCTION fNonUnicode(p_inputVar LONGTEXT )
RETURNS LONGTEXT
BEGIN
IF (p_inputVar IS NULL OR p_inputVar = '') THEN RETURN '';
END IF;
DECLARE v_RT LONGTEXT;
DECLARE v_SIGN_CHARS NVARCHAR(256);
DECLARE v_UNSIGN_CHARS NVARCHAR (256);
SET v_SIGN_CHARS = Concat(N'ăâđêôơưàảãạáằẳẵặắầẩẫậấèẻẽẹéềểễệếìỉĩịíòỏõọóồổỗộốờởỡợớùủũụúừửữựứỳỷỹỵýĂÂĐÊÔƠƯÀẢÃẠÁẰẲẴẶẮẦẨẪẬẤÈẺẼẸÉỀỂỄỆẾÌỈĨỊÍÒỎÕỌÓỒỔỖỘỐỜỞỠỢỚÙỦŨỤÚỪỬỮỰỨỲỶỸỴÝ' , NCHAR(272) + NCHAR(208));
SET v_UNSIGN_CHARS = N'aadeoouaaaaaaaaaaaaaaaeeeeeeeeeeiiiiiooooooooooooooouuuuuuuuuuyyyyyAADEOOUAAAAAAAAAAAAAAAEEEEEEEEEEIIIIIOOOOOOOOOOOOOOOUUUUUUUUUUYYYYYDD';
DECLARE v_COUNTER int;
DECLARE v_COUNTER1 int;
SET v_COUNTER = 1;
WHILE (v_COUNTER <= CHAR_LENGTH(RTRIM(p_inputVar)))
DO
SET v_COUNTER1 = 1;
WHILE (v_COUNTER1 <= CHAR_LENGTH(RTRIM(v_SIGN_CHARS)) + 1)
DO
IF UNICODE(SUBSTRING(v_SIGN_CHARS, v_COUNTER1,1)) = UNICODE(SUBSTRING(p_inputVar,v_COUNTER ,1))
THEN
IF v_COUNTER = 1 THEN
SET p_inputVar = CONCAT(SUBSTRING(v_UNSIGN_CHARS, v_COUNTER1,1) , SUBSTRING(p_inputVar, v_COUNTER+1,CHAR_LENGTH(RTRIM(p_inputVar))-1));
ELSE
SET p_inputVar = CONCAT(SUBSTRING(p_inputVar, 1, v_COUNTER-1) ,SUBSTRING(v_UNSIGN_CHARS, v_COUNTER1,1) , SUBSTRING(p_inputVar, v_COUNTER+1,CHAR_LENGTH(RTRIM(p_inputVar))- v_COUNTER));
END IF;
BREAK
END IF;
SET v_COUNTER1 = v_COUNTER1 +1;
END WHILE;
SET v_COUNTER = v_COUNTER +1;
END WHILE;
-- SET #inputVar = replace(#inputVar,' ','-')
RETURN p_inputVar;
END;
//
DELIMITER ;
But Error:You have an error in your SQL syntax; check the manual that corresponds to your MariaDB server version for the right syntax to use near 'DECLARE v_RT LONGTEXT;
Finnaly: I want to use:fNonUnicode("Xin chào các bạn") return Xin chao cac ban
MySQL Function to remove accents and special characters
DROP FUNCTION IF EXISTS fn_remove_accents;
DELIMITER |
CREATE FUNCTION fn_remove_accents( textvalue VARCHAR(10000) ) RETURNS VARCHAR(10000)
BEGIN
SET #textvalue = textvalue;
-- ACCENTS
SET #withaccents = 'ŠšŽžÀÁÂÃÄÅÆÇÈÉÊËÌÍÎÏÑÒÓÔÕÖØÙÚÛÜÝŸÞàáâãäåæçèéêëìíîïñòóôõöøùúûüýÿþƒ';
SET #withoutaccents = 'SsZzAAAAAAACEEEEIIIINOOOOOOUUUUYYBaaaaaaaceeeeiiiinoooooouuuuyybf';
SET #count = LENGTH(#withaccents);
WHILE #count > 0 DO
SET #textvalue = REPLACE(#textvalue, SUBSTRING(#withaccents, #count, 1), SUBSTRING(#withoutaccents, #count, 1));
SET #count = #count - 1;
END WHILE;
-- SPECIAL CHARS
SET #special = '!##$%¨&*()_+=§¹²³£¢¬"`´{[^~}]<,>.:;?/°ºª+*|\\''';
SET #count = LENGTH(#special);
WHILE #count > 0 do
SET #textvalue = REPLACE(#textvalue, SUBSTRING(#special, #count, 1), '');
SET #count = #count - 1;
END WHILE;
RETURN #textvalue;
END
|
DELIMITER ;
please try with code below
DROP FUNCTION IF EXISTS fn_remove_accents;
DELIMITER //
CREATE FUNCTION fn_remove_accents(textvalue TEXT)
RETURNS TEXT
BEGIN
SET #textvalue = textvalue;
-- ACCENTS
SET #withaccents = 'ăâđêôơưàảãạáằẳẵặắầẩẫậấèẻẽẹéềểễệếìỉĩịíòỏõọóồổỗộốờởỡợớùủũụúừửữựứỳỷỹỵýĂÂĐÊÔƠƯÀẢÃẠÁẰẲẴẶẮẦẨẪẬẤÈẺẼẸÉỀỂỄỆẾÌỈĨỊÍÒỎÕỌÓỒỔỖỘỐỜỞỠỢỚÙỦŨỤÚỪỬỮỰỨỲỶỸỴÝ';
SET #withoutaccents = 'aadeoouaaaaaaaaaaaaaaaeeeeeeeeeeiiiiiooooooooooooooouuuuuuuuuuyyyyyAADEOOUAAAAAAAAAAAAAAAEEEEEEEEEEIIIIIOOOOOOOOOOOOOOOUUUUUUUUUUYYYYY';
SET #count = LENGTH(#withaccents);
WHILE #count > 0 DO
SET #textvalue = REPLACE(#textvalue, SUBSTRING(#withaccents, #count, 1), SUBSTRING(#withoutaccents, #count, 1));
SET #count = #count - 1;
END WHILE;
RETURN #textvalue;
END
//
DELIMITER ;

How to convert text to proper case using mysql command line

What is the best method to convert text to proper case using MYSQL command line
Example: JOHN DOE convert to John Doe
as answered in a previous post here Capitalize first letter. MySQL if you create the following function in the database, then it can be used on the command line also, this will capitalise every word on the string.
DELIMITER ||
CREATE FUNCTION `UC_Words`( str VARCHAR(255) ) RETURNS VARCHAR(255) CHARSET utf8_general_ci
BEGIN
DECLARE c CHAR(1);
DECLARE s VARCHAR(255);
DECLARE i INT DEFAULT 1;
DECLARE bool INT DEFAULT 1;
DECLARE punct CHAR(17) DEFAULT ' ()[]{},.-_!#;:?/';
SET s = LCASE( str );
WHILE i < LENGTH( str ) DO
BEGIN
SET c = SUBSTRING( s, i, 1 );
IF LOCATE( c, punct ) > 0 THEN
SET bool = 1;
ELSEIF bool=1 THEN
BEGIN
IF c >= 'a' AND c <= 'z' THEN
BEGIN
SET s = CONCAT(LEFT(s,i-1),UCASE(c),SUBSTRING(s,i+1));
SET bool = 0;
END;
ELSEIF c >= '0' AND c <= '9' THEN
SET bool = 0;
END IF;
END;
END IF;
SET i = i+1;
END;
END WHILE;
RETURN s;
END ||
DELIMITER ;

MySQL substring in function not returning whitespace

I have a function that is for changing text into proper case.
CREATE FUNCTION `fpropercasetest` (p_Value VARCHAR(8000))
RETURNS VARCHAR(8000)
BEGIN
DECLARE v_i INT; -- counter
DECLARE v_ProperCaseText VARCHAR(5000);
DECLARE v_Word VARCHAR(1000);
DECLARE v_isWhiteSpace TINYINT(1);
DECLARE v_c CHAR(1);
SET v_Word = '';
SET v_i = 1;
SET v_isWhiteSpace = 1;
SET v_ProperCaseText = '';
SET p_Value = LOWER(p_Value);
WHILE (v_i <= LENGTH(p_Value)+1) DO
SET v_c = SUBSTRING(p_Value,v_i,1);
IF v_isWhiteSpace = 1 THEN SET v_c = UPPER(v_c); END IF;
SET v_isWhiteSpace = CASE WHEN (ASCII(v_c) BETWEEN 48 AND 58) THEN 0
WHEN (ASCII(v_c) BETWEEN 64 AND 90) THEN 0
WHEN (ASCII(v_c) BETWEEN 96 AND 123) THEN 0
ELSE 1 END;
IF v_isWhiteSpace = 0 THEN
SET v_Word = CONCAT(v_Word, v_c);
ELSE
SET v_ProperCaseText = CONCAT(v_ProperCaseText, v_Word, v_c);
SET v_Word = '';
END IF;
SET v_i = v_i + 1;
END WHILE;
return v_ProperCaseText;
END;
You can test with the following
SELECT fpropercasetest("this is just some text for you to test with");
When I entered any text with spaces I noticed that it just didn't register (e.g. with the text "this is some text" it would return "ThisIsSomeText" and it should return "This Is Some Text")
I debugged it with Visual Studio and noticed that substring was just ignoring spaces completely, it returns an empty string.
I'm completely stumped by this, any help will be greatly appreciated. Thanks.
Sorry about the delay, I had a few things to take care of before leaving work, here is what I came up with, it does what you want it to do:
FUNCTION `upper_all`(p_Value VARCHAR(8000)) RETURNS varchar(8000) CHARSET latin1
BEGIN
DECLARE pos INT; -- counter
DECLARE result VARCHAR(1000);
SET p_Value = LOWER(p_Value);
SET p_Value = CONCAT(UCASE(LEFT(p_Value, 1)),LCASE(SUBSTRING(p_Value, 2)));
SET pos = LOCATE(' ',p_Value);
SET result = SUBSTR(p_Value,1,LOCATE(' ',p_Value));
SET p_Value = SUBSTR(p_Value FROM pos);
WHILE (pos > 0) DO
/*SET p_Value = CONCAT(p_Value,UCASE(LEFT(p_Value, pos)),LCASE(SUBSTRING(p_Value, 2)));*/
SET pos = LOCATE(' ',p_Value);
IF pos > 0 THEN
SET pos = pos + 1;
SET p_Value = SUBSTR(p_Value FROM pos);
END IF;
SET p_Value = CONCAT(UCASE(LEFT(p_Value, 1)),LCASE(SUBSTRING(p_Value, 2)));
SET result = CONCAT(result,SUBSTR(p_Value,1,LOCATE(' ',p_Value)));
END WHILE;
SET result = CONCAT(result,p_Value);
return result;
END
I didn't have time to comment it out for you, it should self-explanatory. It could use a little cleanup and optimize the code a bit.
create function fn_title_case
(v_input_string varchar(255))
RETURNS varchar(255)
BEGIN
declare i int;
DECLARE punctuation varchar(17);
declare this_character char(1);
declare output_string varchar(255);
declare boolean_value int;
declare input_length int;
set input_length = char_length(v_input_string);
set boolean_value = 0;
set i = 0;
set punctuation = ' ';
set output_string = '';
begin
-- Loop through each character in the input string
while i <= input_length do
-- Set the current substring to position i with length 1
SET this_character = SUBSTRING( v_input_string, i, 1 );
-- If the current character exists in the punctuation string, i.e. if the current character is a space
IF LOCATE( this_character, punctuation ) > 0 THEN
-- Set the current character to null and the boolean to 1
set this_character = '', output_string = concat(output_string, this_character), boolean_value = 1;
elseif boolean_value=1 then
-- Only if the punctuation (a space) was detected in the previous step,
-- Insert a space and capitalize the letter
SET output_string = concat(output_string, ' ', UCASE(this_character)), boolean_value = 0;
else
-- If the space was NOT detected, add the current character in lower case
set output_string = concat(output_string, LCASE(this_character));
end if;
set i = i+1;
end while;
end;
RETURN output_string;

Create function for an update

I used a column 'Title' in a table 'incident'. This column contains some information .Among this information, three character that indicates the region .these three character are usually found after ('on', ':'). I want to execute a function (mysql) which allows: 1) if the three character taken from the 'Title' column, which are located after 'on', are( kef or bej or jen) so the result will be stored in a column 'test' in the same table. 2) if the first is not achieved then takes the three character which are located after ':' and stored in a column 'test1' in the same table.
there is the code that i used :
delimiter |
CREATE FUNCTION METTER5 (s VARCHAR(2000)) RETURNS VARCHAR(10000)
DETERMINISTIC
BEGIN
DECLARE open INT;
DECLARE close INT;
DECLARE someLimit INT;
DECLARE str VARCHAR(2000);
DECLARE str1 VARCHAR(2000);
DECLARE str2 VARCHAR(2000);
DECLARE str3 VARCHAR(2000);
DECLARE toFind VARCHAR(2000);
DECLARE co VARCHAR(2000);
SET co='';
SET open = 1;
SET close = 1;
SET toFind = s ;
SET someLimit =100;
SET str='';
SET str1='';
SET str2='';
/* SET tofind=concat(tofind,'sur','');*/
SET str =substring(trim(substring_index(s,'sur',-1)),1,3);
SET str1 =substring(trim(substring_index(s,'du',-1)),1,3);
SET str2 =substring(trim(substring_index(s,':',-1)),1,3);
IF (str in ('ZAG','TUN','TOZ','TAT','SOS','SIL','SFX','SBO','RNC','BAR','BEJ','BIZ','BSC','GAB','GAF','JEN','KAI','KAS','KEB','KEF','MAH','MED','MON','NAB')) =1 THEN set co = str ;
ELSE IF ((str not in ('ZAG','TUN','TOZ','TAT','SOS','SIL','SFX','SBO','RNC','BAR','BEJ','BIZ','BSC','GAB','GAF','JEN','KAI','KAS','KEB','KEF','MAH','MED','MON','NAB')) and (str1 in ('ZAG','TUN','TOZ','TAT','SOS','SIL','SFX','SBO','RNC','BAR','BEJ','BIZ','BSC','GAB','GAF','JEN','KAI','KAS','KEB','KEF','MAH','MED','MON','NAB')))=1 THEN set co = str1 ;
ELSE IF ((str1 not in ('ZAG','TUN','TOZ','TAT','SOS','SIL','SFX','SBO','RNC','BAR','BEJ','BIZ','BSC','GAB','GAF','JEN','KAI','KAS','KEB','KEF','MAH','MED','MON','NAB'))and (str2 in ('ZAG','TUN','TOZ','TAT','SOS','SIL','SFX','SBO','RNC','BAR','BEJ','BIZ','BSC','GAB','GAF','JEN','KAI','KAS','KEB','KEF','MAH','MED','MON','NAB')))=1 THEN SET co = str2 ;
ELSE set co = '1' ;
END IF;
END IF;
END IF;
return co;
END |
delimiter;
and there is the query that i used :
update incident set test =METTER5 (Title) WHERE Affected_CI like 'other ci' and open_time between '2015-01-01' and '2015-01-30'
but after the running , there is the problem : Unknown column 'description' in 'field list'
thanks.

mysql question - way to update case for field?

I have some entries in a field that look like this: NEvada city or nevada City... Is there a way to update the database so that entries have initial caps: Nevada City?
You can use:
UPDATE `table` SET
`field` = CONCAT(UPPER(LEFT(`field`, 1)), LOWER(SUBSTRING(`field`, 2)))
But still you will need to modify it to allow a capital Letter for the next word like City...
Source here
UPDATE:
Found this example at MySQL's forum, it is exactly what you need:
DROP FUNCTION IF EXISTS proper;
SET GLOBAL log_bin_trust_function_creators=TRUE;
DELIMITER |
CREATE FUNCTION proper( str VARCHAR(128) )
RETURNS VARCHAR(128)
BEGIN
DECLARE c CHAR(1);
DECLARE s VARCHAR(128);
DECLARE i INT DEFAULT 1;
DECLARE bool INT DEFAULT 1;
DECLARE punct CHAR(17) DEFAULT ' ()[]{},.-_!#;:?/';
SET s = LCASE( str );
WHILE i < LENGTH( str ) DO
BEGIN
SET c = SUBSTRING( s, i, 1 );
IF LOCATE( c, punct ) > 0 THEN
SET bool = 1;
ELSEIF bool=1 THEN
BEGIN
IF c >= 'a' AND c <= 'z' THEN
BEGIN
SET s = CONCAT(LEFT(s,i-1),UCASE(c),SUBSTRING(s,i+1));
SET bool = 0;
END;
ELSEIF c >= '0' AND c <= '9' THEN
SET bool = 0;
END IF;
END;
END IF;
SET i = i+1;
END;
END WHILE;
RETURN s;
END;
|
DELIMITER ;