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;
Related
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 ;
I have a column in a mysql table that users have added data. Some users like to use proper capitalization, some like uppercase words, some all lower case.
What I want to do is change:
CHECK BUILDING.
To:
Check building.
And:
DELIVER PAPERS. UNLOCK DOORS.
To:
Deliver papers. Unlock doors.
I assume a function could do this so I can re-use it.
Any ideas?
I tried this but it does each word not the first word in a sentence.
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
There's no MySQL function to do that. This function capitalize the first letter of every word in a string.
CREATE FUNCTION CAP_FIRST (input VARCHAR(255))
RETURNS VARCHAR(255)
DETERMINISTIC
BEGIN
DECLARE len INT;
DECLARE i INT;
SET len = CHAR_LENGTH(input);
SET input = LOWER(input);
SET i = 0;
WHILE (i < len) DO
IF (MID(input,i,1) = ' ' OR i = 0) THEN
IF (i < len) THEN
SET input = CONCAT(
LEFT(input,i),
UPPER(MID(input,i + 1,1)),
RIGHT(input,len - i - 1)
);
END IF;
END IF;
SET i = i + 1;
END WHILE;
RETURN input;
END;
References link.
I am newbie to MySQL
I am trying to generate random data and put it into table 'data'
But SQL shell says that my sql code have syntax error
But I can't find why
DECLARE #counter smallint;
DECLARE #A BOOLEAN;
DECLARE #B BOOLEAN;
DECLARE #C int(4);
DECLARE #LABEL BOOLEAN;
SET #counter = 1;
WHILE #counter < 100
BEGIN
IF 0.5 > RAND()
SET #A = TRUE;
ELSE
SET #A = FALSE;
IF 0.5 > RAND()
SET #B = TRUE;
ELSE
SET #B = FALSE;
SET #C = RAND() * 10
SET #LABEL = #A ^ #B OR #LABEL > 5
INSERT INTO data (A,B,C,LABEL) VALUES (#A,#B,#C,#LABEL)
#count = #count +1
END
It says that I have syntax problem
from declaring variables
can you help me?
Is missing some syntax words:
IF... THEN ... ELSE ... END IF;
WHILE ... DO ... END WHILE;
Is important understand that user variables are written as #var_name, so user-defined variables are session-specific. That is, a user variable defined by one client cannot be seen or used by other clients. All variables for a given client session are automatically freed when that client exits. In this case, I think that is not necessary.
SET, either = or := can be used as the assignment operator.
Try this:
delimiter //
CREATE PROCEDURE TEST()
BEGIN
DECLARE counter smallint;
DECLARE A BOOLEAN;
DECLARE B BOOLEAN;
DECLARE C int(4);
DECLARE LABEL BOOLEAN;
SET counter = 1;
WHILE counter < 100 DO
IF 0.5 > RAND() THEN
SET A = TRUE;
ELSE
SET A = FALSE;
END IF;
IF 0.5 > RAND() THEN
SET B = TRUE;
ELSE
SET B = FALSE;
END IF;
SET C = RAND() * 10;
IF A ^ B OR LABEL > 5 THEN
SET LABEL = TRUE;
ELSE
SET LABEL = FALSE;
END IF;
INSERT INTO data (A,B,C,LABEL) VALUES (A,B,C,LABEL);
SET counter = counter +1;
END WHILE;
END//
try this,
DECLARE #counter smallint,
DECLARE #A BOOLEAN,
DECLARE #B BOOLEAN,
DECLARE #C int(4),
DECLARE #LABEL BOOLEAN;
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.
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 ;