Capitalize first letter. MySQL - mysql

Does any one know the equivalent to this TSQL in MySQL parlance?
I am trying to capitalize the first letter of each entry.
UPDATE tb_Company SET CompanyIndustry = UPPER(LEFT(CompanyIndustry, 1))
+ SUBSTRING(CompanyIndustry, 2, LEN(CompanyIndustry))

It's almost the same, you just have to change to use the CONCAT() function instead of the + operator :
UPDATE tb_Company
SET CompanyIndustry = CONCAT(UCASE(LEFT(CompanyIndustry, 1)),
SUBSTRING(CompanyIndustry, 2));
This would turn hello to Hello, wOrLd to WOrLd, BLABLA to BLABLA, etc. If you want to upper-case the first letter and lower-case the other, you just have to use LCASE function :
UPDATE tb_Company
SET CompanyIndustry = CONCAT(UCASE(LEFT(CompanyIndustry, 1)),
LCASE(SUBSTRING(CompanyIndustry, 2)));
Note that UPPER and UCASE do the same thing.

Vincents excellent answer for Uppercase First Letter works great for the first letter only capitalization of an entire column string..
BUT what if you want to Uppercase the First Letter of EVERY word in the strings of a table column?
eg: "Abbeville High School"
I hadn't found an answer to this in Stackoverflow. I had to cobble together a few answers I found in Google to provide a solid solution to the above example. Its not a native function but a user created function which MySQL version 5+ allows.
If you have Super/Admin user status on MySQL or have a local mysql installation on your own computer you can create a FUNCTION (like a stored procedure) which sits in your database and can be used in all future SQL query on any part of the db.
The function I created allows me to use this new function I called "UC_Words" just like the built in native functions of MySQL so that I can update a complete column like this:
UPDATE Table_name
SET column_name = UC_Words(column_name)
To insert the function code, I changed the MySQL standard delimiter(;) whilst creating the function, and then reset it back to normal after the function creation script. I also personally wanted the output to be in UTF8 CHARSET too.
Function creation =
DELIMITER ||
CREATE FUNCTION `UC_Words`( str VARCHAR(255) ) RETURNS VARCHAR(255) CHARSET utf8 DETERMINISTIC
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 ;
This works a treat outputting Uppercase first letters on multiple words within a string.
Assuming your MySQL login username has sufficient privileges - if not, and you cant set up a temporary DB on your personal machine to convert your tables, then ask your shared hosting provider if they will set this function for you.

You can use a combination of UCASE(), MID() and CONCAT():
SELECT CONCAT(UCASE(MID(name,1,1)),MID(name,2)) AS name FROM names;

mysql> SELECT schedule_type AS Schedule FROM ad_campaign limit 1;
+----------+
| Schedule |
+----------+
| ENDDATE |
+----------+
1 row in set (0.00 sec)
mysql> SELECT CONCAT(UCASE(MID(schedule_type,1,1)),LCASE(MID(schedule_type,2))) AS Schedule FROM ad_campaign limit 1;
+----------+
| Schedule |
+----------+
| Enddate |
+----------+
1 row in set (0.00 sec)
http://dev.mysql.com/doc/refman/5.0/en/string-functions.html#function_mid

This is working nicely.
UPDATE state SET name = CONCAT(UCASE(LEFT(name, 1)), LCASE(SUBSTRING(name, 2)));

http://forge.mysql.com/tools/tool.php?id=201
If there are more than 1 word in the column, then this will not work as shown below.
The UDF mentioned above may help in such case.
mysql> select * from names;
+--------------+
| name |
+--------------+
| john abraham |
+--------------+
1 row in set (0.00 sec)
mysql> SELECT CONCAT(UCASE(MID(name,1,1)),MID(name,2)) AS name FROM names;
+--------------+
| name |
+--------------+
| John abraham |
+--------------+
1 row in set (0.00 sec)
Or maybe this one will help...
https://github.com/mysqludf/lib_mysqludf_str#str_ucwords

UPDATE tb_Company SET CompanyIndustry = UCASE(LEFT(CompanyIndustry, 1)) +
SUBSTRING(CompanyIndustry, 2, LEN(CompanyIndustry))

CREATE A FUNCTION:
CREATE DEFINER=`root`#`localhost` FUNCTION `UC_FIRST`(`oldWord` VARCHAR(255))
RETURNS varchar(255) CHARSET utf8
RETURN CONCAT( UCASE( LEFT(oldWord, 1)), LCASE(SUBSTRING(oldWord, 2)))
USE THE FUNCTION
UPDATE tbl_name SET col_name = UC_FIRST(col_name);

If anyone try to capitalize the every word separate by space...
CREATE FUNCTION response(name VARCHAR(40)) RETURNS VARCHAR(200) DETERMINISTIC
BEGIN
set #m='';
set #c=0;
set #l=1;
while #c <= char_length(name)-char_length(replace(name,' ','')) do
set #c = #c+1;
set #p = SUBSTRING_INDEX(name,' ',#c);
set #k = substring(name,#l,char_length(#p)-#l+1);
set #l = char_length(#k)+2;
set #m = concat(#m,ucase(left(#k,1)),lcase(substring(#k,2)),' ');
end while;
return trim(#m);
END;
CREATE PROCEDURE updateNames()
BEGIN
SELECT response(name) AS name FROM names;
END;
Result
+--------------+
| name |
+--------------+
| Abdul Karim |
+--------------+

This should work nicely:
UPDATE tb_Company SET CompanyIndustry =
CONCAT(UPPER(LEFT(CompanyIndustry, 1)), SUBSTRING(CompanyIndustry, 2))

UPDATE users
SET first_name = CONCAT(UCASE(LEFT(first_name, 1)),
LCASE(SUBSTRING(first_name, 2)))
,last_name = CONCAT(UCASE(LEFT(last_name, 1)),
LCASE(SUBSTRING(last_name, 2)));

select CONCAT(UCASE(LEFT('CHRIS', 1)),SUBSTRING(lower('CHRIS'),2));
Above statement can be used for first letter CAPS and rest as lower case.

The solution in PostgreSQL (as far as googling may lead to this page)
INITCAP(firstname || ' ' || lastname) AS fullname

Uso algo simples assim ;)
DELIMITER $$
DROP FUNCTION IF EXISTS `uc_frist` $$
CREATE FUNCTION `uc_frist` (str VARCHAR(200)) RETURNS varchar(200)
BEGIN
set str:= lcase(str);
set str:= CONCAT(UCASE(LEFT(str, 1)),SUBSTRING(str, 2));
set str:= REPLACE(str, ' a', ' A');
set str:= REPLACE(str, ' b', ' B');
set str:= REPLACE(str, ' c', ' C');
set str:= REPLACE(str, ' d', ' D');
set str:= REPLACE(str, ' e', ' E');
set str:= REPLACE(str, ' f', ' F');
set str:= REPLACE(str, ' g', ' G');
set str:= REPLACE(str, ' h', ' H');
set str:= REPLACE(str, ' i', ' I');
set str:= REPLACE(str, ' j', ' J');
set str:= REPLACE(str, ' k', ' K');
set str:= REPLACE(str, ' l', ' L');
set str:= REPLACE(str, ' m', ' M');
set str:= REPLACE(str, ' n', ' N');
set str:= REPLACE(str, ' o', ' O');
set str:= REPLACE(str, ' p', ' P');
set str:= REPLACE(str, ' q', ' Q');
set str:= REPLACE(str, ' r', ' R');
set str:= REPLACE(str, ' s', ' S');
set str:= REPLACE(str, ' t', ' T');
set str:= REPLACE(str, ' u', ' U');
set str:= REPLACE(str, ' v', ' V');
set str:= REPLACE(str, ' w', ' W');
set str:= REPLACE(str, ' x', ' X');
set str:= REPLACE(str, ' y', ' Y');
set str:= REPLACE(str, ' z', ' Z');
return str;
END $$
DELIMITER ;

Related

Creating funcion for short date in spanish

Hi guys this function gives me this error: "Something wrong in line 35." (RETURN diaCompleto;), I dont know whats wrong with the code below anyway can point me out in the correct direction, tyvm.
DELIMITER $$
CREATE FUNCTION DIA_FECHA(fecha date)
RETURNS VARCHAR(8)
BEGIN
DECLARE nomDia VARCHAR(6);
DECLARE dia VARCHAR(2);
DECLARE diaCompleto VARCHAR(8);
SET dia = LPAD(DAY(fecha),2,'0');
IF(DAYOFWEEK(fecha) = 1) THEN
SET nomDia = 'DOM - ';
IF(DAYOFWEEK(fecha) = 2) THEN
SET nomDia = 'LUN - ';
IF(DAYOFWEEK(fecha) = 3) THEN
SET nomDia = 'MAR - ';
IF(DAYOFWEEK(fecha) = 4) THEN
SET nomDia = 'MIE - ';
IF(DAYOFWEEK(fecha) = 5) THEN
SET nomDia = 'JUE - ';
IF(DAYOFWEEK(fecha) = 6) THEN
SET nomDia = 'VIE - ';
IF(DAYOFWEEK(fecha) = 7) THEN
SET nomDia = 'SAB - ';
SET diaCompleto = CONCAT(nomDia,dia);
RETURN diaCompleto;
END$$
DELIMITER ;
The reason for your syntax error is that you need to use END IF; after each IF/THEN. See examples in the manual: https://dev.mysql.com/doc/refman/8.0/en/if.html
I think you don't need to write this function at all. Instead, you could use MySQL's DATE_FORMAT() function. It supports locale-aware names for days of the week.
mysql> set lc_time_names = 'es_ES';
mysql> select date_format(curdate(), '%a - %d') as diaCompleto;
+-------------+
| diaCompleto |
+-------------+
| sáb - 19 |
+-------------+

Mysql search & replace with random characters

I have in text some URLS src="https://example.com/public/images/someimage.jpg?itok=WDGFySy"
I need remove in every url this garbage token ?itok=WDGFySy, all tokens obviously are random :).
I try do it directly in database like this:
UPDATE wp_posts SET post_content = REPLACE(post_content, 'itok=[[:xdigit:]]{8}', '') WHERE post_content LIKE 'itok=[[:xdigit:]]{8}
';
But i cant find any of this tokens like this. LIKE this [a-fA-F0-9]{8} also wont help. Any advice? Thank you for any suggestions.
You can only use regex if you have MySQL 8.0.
However, if your links are in separate fields, it is possible to create and use SP to clean them up:
DELIMITER $$
CREATE FUNCTION CLEANUP(
aString VARCHAR(255)
, aName VARCHAR(15)
)
RETURNS VARCHAR(255)
BEGIN
SET #u = SUBSTRING_INDEX(aString, '?', 1);
SET #q = SUBSTRING_INDEX(aString, '?', -1);
IF #q = aString THEN
RETURN aString; -- no '?' char found
ELSE
SET #f = LOCATE(CONCAT(aName, '='), #q);
SET #query = IF(#f > 1, SUBSTR(#q, 1, #f - 1), '');
IF #f > 0 THEN
SET #t = LOCATE('&', #q, #f + LENGTH(aName) + 1);
IF #t > 0 THEN
SET #query = CONCAT(#query, SUBSTR(#q, #t + 1));
END IF;
END IF;
IF #query = '' THEN
RETURN #u;
ELSE
RETURN CONCAT(#u, '?', TRIM('&' FROM #query));
END IF;
END IF;
END
$$
DELIMITER ;
Then:
SELECT
CLEANUP('https://example.com/public/images/someimage.jpg?itok=WDGFySy&b=2', 'itok')
, CLEANUP('https://example.com/public/images/someimage.jpg?itok=WDGFySy', 'itok')
, CLEANUP('https://example.com/public/images/someimage.jpg?a=1&itok=WDGFySy', 'itok')
, CLEANUP('https://example.com/public/images/someimage.jpg?a=1&itok=WDGFySy&b=2', 'itok')
;

sql - select column but remove non alphanumeric in result [duplicate]

I'm working on a routine that compares strings, but for better efficiency I need to remove all characters that are not letters or numbers.
I'm using multiple REPLACE functions now, but maybe there is a faster and nicer solution ?
Using MySQL 8.0 or higher
Courtesy of michal.jakubeczy's answer below, replacing by Regex is now supported by MySQL:
UPDATE {table} SET {column} = REGEXP_REPLACE({column}, '[^0-9a-zA-Z ]', '')
Using MySQL 5.7 or lower
Regex isn't supported here. I had to create my own function called alphanum which stripped the chars for me:
DROP FUNCTION IF EXISTS alphanum;
DELIMITER |
CREATE FUNCTION alphanum( str CHAR(255) ) RETURNS CHAR(255) DETERMINISTIC
BEGIN
DECLARE i, len SMALLINT DEFAULT 1;
DECLARE ret CHAR(255) DEFAULT '';
DECLARE c CHAR(1);
IF str IS NOT NULL THEN
SET len = CHAR_LENGTH( str );
REPEAT
BEGIN
SET c = MID( str, i, 1 );
IF c REGEXP '[[:alnum:]]' THEN
SET ret=CONCAT(ret,c);
END IF;
SET i = i + 1;
END;
UNTIL i > len END REPEAT;
ELSE
SET ret='';
END IF;
RETURN ret;
END |
DELIMITER ;
Now I can do:
select 'This works finally!', alphanum('This works finally!');
and I get:
+---------------------+---------------------------------+
| This works finally! | alphanum('This works finally!') |
+---------------------+---------------------------------+
| This works finally! | Thisworksfinally |
+---------------------+---------------------------------+
1 row in set (0.00 sec)
Hurray!
From a performance point of view,
(and on the assumption that you read more than you write)
I think the best way would be to pre calculate and store a stripped version of the column,
This way you do the transform less.
You can then put an index on the new column and get the database to do the work for you.
SELECT teststring REGEXP '[[:alnum:]]+';
SELECT * FROM testtable WHERE test REGEXP '[[:alnum:]]+';
See: http://dev.mysql.com/doc/refman/5.1/en/regexp.html
Scroll down to the section that says: [:character_class:]
If you want to manipulate strings the fastest way will be to use a str_udf, see:
https://github.com/hholzgra/mysql-udf-regexp
Since MySQL 8.0 you can use regular expression to remove non alphanumeric characters from a string. There is method REGEXP_REPLACE
Here is the code to remove non-alphanumeric characters:
UPDATE {table} SET {column} = REGEXP_REPLACE({column}, '[^0-9a-zA-Z ]', '')
Straight and battletested solution for latin and cyrillic characters:
DELIMITER //
CREATE FUNCTION `remove_non_numeric_and_letters`(input TEXT)
RETURNS TEXT
BEGIN
DECLARE output TEXT DEFAULT '';
DECLARE iterator INT DEFAULT 1;
WHILE iterator < (LENGTH(input) + 1) DO
IF SUBSTRING(input, iterator, 1) IN
('0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z', 'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z', 'А', 'Б', 'В', 'Г', 'Д', 'Е', 'Ж', 'З', 'И', 'Й', 'К', 'Л', 'М', 'Н', 'О', 'П', 'Р', 'С', 'Т', 'У', 'Ф', 'Х', 'Ц', 'Ч', 'Ш', 'Щ', 'Ъ', 'Ы', 'Ь', 'Э', 'Ю', 'Я', 'а', 'б', 'в', 'г', 'д', 'е', 'ж', 'з', 'и', 'й', 'к', 'л', 'м', 'н', 'о', 'п', 'р', 'с', 'т', 'у', 'ф', 'х', 'ц', 'ч', 'ш', 'щ', 'ъ', 'ы', 'ь', 'э', 'ю', 'я')
THEN
SET output = CONCAT(output, SUBSTRING(input, iterator, 1));
END IF;
SET iterator = iterator + 1;
END WHILE;
RETURN output;
END //
DELIMITER ;
Usage:
-- outputs "hello12356"
SELECT remove_non_numeric_and_letters('hello - 12356-привет ""]')
The fastest way I was able to find (and using ) is with convert().
from Doc. CONVERT() with USING is used to convert data between different character sets.
Example:
convert(string USING ascii)
In your case the right character set will be self defined
NOTE from Doc. The USING form of CONVERT() is available as of 4.1.0.
Based on the answer by Ryan Shillington, modified to work with strings longer than 255 characters and preserving spaces from the original string.
FYI there is lower(str) in the end.
I used this to compare strings:
DROP FUNCTION IF EXISTS spacealphanum;
DELIMITER $$
CREATE FUNCTION `spacealphanum`( str TEXT ) RETURNS TEXT CHARSET utf8
BEGIN
DECLARE i, len SMALLINT DEFAULT 1;
DECLARE ret TEXT DEFAULT '';
DECLARE c CHAR(1);
SET len = CHAR_LENGTH( str );
REPEAT
BEGIN
SET c = MID( str, i, 1 );
IF c REGEXP '[[:alnum:]]' THEN
SET ret=CONCAT(ret,c);
ELSEIF c = ' ' THEN
SET ret=CONCAT(ret," ");
END IF;
SET i = i + 1;
END;
UNTIL i > len END REPEAT;
SET ret = lower(ret);
RETURN ret;
END $$
DELIMITER ;
Be careful, characters like ’ or » are considered as alpha by MySQL.
It better to use something like :
IF c BETWEEN 'a' AND 'z' OR c BETWEEN 'A' AND 'Z' OR c BETWEEN '0' AND
'9' OR c = '-' THEN
I have written this UDF. However, it only trims special characters at the beginning of the string. It also converts the string to lower case. You can update this function if desired.
DELIMITER //
DROP FUNCTION IF EXISTS DELETE_DOUBLE_SPACES//
CREATE FUNCTION DELETE_DOUBLE_SPACES ( title VARCHAR(250) )
RETURNS VARCHAR(250) DETERMINISTIC
BEGIN
DECLARE result VARCHAR(250);
SET result = REPLACE( title, ' ', ' ' );
WHILE (result <> title) DO
SET title = result;
SET result = REPLACE( title, ' ', ' ' );
END WHILE;
RETURN result;
END//
DROP FUNCTION IF EXISTS LFILTER//
CREATE FUNCTION LFILTER ( title VARCHAR(250) )
RETURNS VARCHAR(250) DETERMINISTIC
BEGIN
WHILE (1=1) DO
IF( ASCII(title) BETWEEN ASCII('a') AND ASCII('z')
OR ASCII(title) BETWEEN ASCII('A') AND ASCII('Z')
OR ASCII(title) BETWEEN ASCII('0') AND ASCII('9')
) THEN
SET title = LOWER( title );
SET title = REPLACE(
REPLACE(
REPLACE(
title,
CHAR(10), ' '
),
CHAR(13), ' '
) ,
CHAR(9), ' '
);
SET title = DELETE_DOUBLE_SPACES( title );
RETURN title;
ELSE
SET title = SUBSTRING( title, 2 );
END IF;
END WHILE;
END//
DELIMITER ;
SELECT LFILTER(' !##$%^&*()_+1a b');
Also, you could use regular expressions but this requires installing a MySql extension.
This can be done with a regular expression replacer function I posted in another answer and have blogged about here. It may not be the most efficient solution possible and might look overkill for the job in hand - but like a Swiss army knife, it may come in useful for other reasons.
It can be seen in action removing all non-alphanumeric characters in this Rextester online demo.
SQL (excluding the function code for brevity):
SELECT txt,
reg_replace(txt,
'[^a-zA-Z0-9]+',
'',
TRUE,
0,
0
) AS `reg_replaced`
FROM test;
I had a similar problem with trying to match last names in our database that were slightly different. For example, sometimes people entered the same person's name as "McDonald" and also as "Mc Donald", or "St John" and "St. John".
Instead of trying to convert the Mysql data, I solved the problem by creating a function (in PHP) that would take a string and create an alpha-only regular expression:
function alpha_only_regex($str) {
$alpha_only = str_split(preg_replace('/[^A-Z]/i', '', $str));
return '^[^a-zA-Z]*'.implode('[^a-zA-Z]*', $alpha_only).'[^a-zA-Z]*$';
}
Now I can search the database with a query like this:
$lastname_regex = alpha_only_regex($lastname);
$query = "SELECT * FROM my_table WHERE lastname REGEXP '$lastname_regex';
So far, the only alternative approach less complicated than the other answers here is to determine the full set of special characters of the column, i.e. all the special characters that are in use in that column at the moment, and then do a sequential replace of all those characters, e.g.
update pages set slug = lower(replace(replace(replace(replace(name, ' ', ''), '-', ''), '.', ''), '&', '')); # replacing just space, -, ., & only
.
This is only advisable on a known set of data, otherwise it's
trivial for some special characters to slip past with a
blacklist approach instead of a whitelist approach.
Obviously, the simplest way is to pre-validate the data outside of sql due to the lack of robust built-in whitelisting (e.g. via a regex replace).
I needed to get only alphabetic characters of a string in a procedure, and did:
SET #source = "whatever you want";
SET #target = '';
SET #i = 1;
SET #len = LENGTH(#source);
WHILE #i <= #len DO
SET #char = SUBSTRING(#source, #i, 1);
IF ((ORD(#char) >= 65 && ORD(#char) <= 90) || (ORD(#char) >= 97 && ORD(#char) <= 122)) THEN
SET #target = CONCAT(#target, #char);
END IF;
SET #i = #i + 1;
END WHILE;
Needed to replace non-alphanumeric characters rather than remove non-alphanumeric characters so I have created this based on Ryan Shillington's alphanum. Works for strings up to 255 characters in length
DROP FUNCTION IF EXISTS alphanumreplace;
DELIMITER |
CREATE FUNCTION alphanumreplace( str CHAR(255), d CHAR(32) ) RETURNS CHAR(255)
BEGIN
DECLARE i, len SMALLINT DEFAULT 1;
DECLARE ret CHAR(32) DEFAULT '';
DECLARE c CHAR(1);
SET len = CHAR_LENGTH( str );
REPEAT
BEGIN
SET c = MID( str, i, 1 );
IF c REGEXP '[[:alnum:]]' THEN SET ret=CONCAT(ret,c);
ELSE SET ret=CONCAT(ret,d);
END IF;
SET i = i + 1;
END;
UNTIL i > len END REPEAT;
RETURN ret;
END |
DELIMITER ;
Example:
select 'hello world!',alphanum('hello world!'),alphanumreplace('hello world!','-');
+--------------+--------------------------+-------------------------------------+
| hello world! | alphanum('hello world!') | alphanumreplace('hello world!','-') |
+--------------+--------------------------+-------------------------------------+
| hello world! | helloworld | hello-world- |
+--------------+--------------------------+-------------------------------------+
You'll need to add the alphanum function seperately if you want that, I just have it here for the example.
I tried a few solutions but at the end used replace. My data set is part numbers and I fairly know what to expect. But just for sanity, I used PHP to build the long query:
$dirty = array(' ', '-', '.', ',', ':', '?', '/', '!', '&', '#');
$query = 'part_no';
foreach ($dirty as $dirt) {
$query = "replace($query,'$dirt','')";
}
echo $query;
This outputs something I used to get a headache from:
replace(replace(replace(replace(replace(replace(replace(replace(replace(replace(part_no,' ',''),'-',''),'.',''),',',''),':',''),'?',''),'/',''),'!',''),'&',''),'#','')
if you are using php then....
try{
$con = new PDO ("mysql:host=localhost;dbname=dbasename","root","");
}
catch(PDOException $e){
echo "error".$e-getMessage();
}
$select = $con->prepare("SELECT * FROM table");
$select->setFetchMode(PDO::FETCH_ASSOC);
$select->execute();
while($data=$select->fetch()){
$id = $data['id'];
$column = $data['column'];
$column = preg_replace("/[^a-zA-Z0-9]+/", " ", $column); //remove all special characters
$update = $con->prepare("UPDATE table SET column=:column WHERE id='$id'");
$update->bindParam(':column', $column );
$update->execute();
// echo $column."<br>";
}
the alphanum function (self answered) have a bug, but I don't know why.
For text "cas synt ls 75W140 1L" return "cassyntls75W1401", "L" from the end is missing some how.
Now I use
delimiter //
DROP FUNCTION IF EXISTS alphanum //
CREATE FUNCTION alphanum(prm_strInput varchar(255))
RETURNS VARCHAR(255)
DETERMINISTIC
BEGIN
DECLARE i INT DEFAULT 1;
DECLARE v_char VARCHAR(1);
DECLARE v_parseStr VARCHAR(255) 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
//
(found on google)
Probably a silly suggestion compared to others:
if(!preg_match("/^[a-zA-Z0-9]$/",$string)){
$sortedString=preg_replace("/^[a-zA-Z0-9]+$/","",$string);
}

How to split the name string in mysql?

How to split the name string in mysql ?
E.g.:
name
-----
Sachin ramesh tendulkar
Rahul dravid
Split the name like firstname,middlename,lastname:
firstname middlename lastname
--------- ------------ ------------
sachin ramesh tendulkar
rahul dravid
I've separated this answer into two(2) methods. The first method will separate your fullname field into first, middle, and last names. The middle name will show as NULL if there is no middle name.
SELECT
SUBSTRING_INDEX(SUBSTRING_INDEX(fullname, ' ', 1), ' ', -1) AS first_name,
If( length(fullname) - length(replace(fullname, ' ', ''))>1,
SUBSTRING_INDEX(SUBSTRING_INDEX(fullname, ' ', 2), ' ', -1) ,NULL)
as middle_name,
SUBSTRING_INDEX(SUBSTRING_INDEX(fullname, ' ', 3), ' ', -1) AS last_name
FROM registeredusers
This second method considers the middle name as part of the lastname. We will only select a firstname and lastname column from your fullname field.
SELECT
SUBSTRING_INDEX(SUBSTRING_INDEX(fullname, ' ', 1), ' ', -1) AS first_name,
TRIM( SUBSTR(fullname, LOCATE(' ', fullname)) ) AS last_name
FROM registeredusers
There's a bunch of cool things you can do with substr, locate, substring_index, etc. Check the manual for some real confusion. http://dev.mysql.com/doc/refman/5.0/en/string-functions.html
There is no string split function in MySQL. so you have to create your own function. This will help you. More details at this link.
Function:
CREATE FUNCTION SPLIT_STR(
x VARCHAR(255),
delim VARCHAR(12),
pos INT
)
RETURNS VARCHAR(255)
RETURN REPLACE(SUBSTRING(SUBSTRING_INDEX(x, delim, pos),
LENGTH(SUBSTRING_INDEX(x, delim, pos -1)) + 1),
delim, '');
Usage:
SELECT SPLIT_STR(string, delimiter, position)
Example:
SELECT SPLIT_STR('a|bb|ccc|dd', '|', 3) as third;
+-------+
| third |
+-------+
| ccc |
+-------+
Well, nothing I used worked, so I decided creating a real simple split function, hope it helps:
DECLARE inipos INTEGER;
DECLARE endpos INTEGER;
DECLARE maxlen INTEGER;
DECLARE item VARCHAR(100);
DECLARE delim VARCHAR(1);
SET delim = '|';
SET inipos = 1;
SET fullstr = CONCAT(fullstr, delim);
SET maxlen = LENGTH(fullstr);
REPEAT
SET endpos = LOCATE(delim, fullstr, inipos);
SET item = SUBSTR(fullstr, inipos, endpos - inipos);
IF item <> '' AND item IS NOT NULL THEN
USE_THE_ITEM_STRING;
END IF;
SET inipos = endpos + 1;
UNTIL inipos >= maxlen END REPEAT;
You can use bewlo one also:
SELECT SUBSTRING_INDEX(Name, ' ', 1) AS fname,
SUBSTRING_INDEX(SUBSTRING_INDEX(Name,' ', 2), ' ',-1) AS mname,
SUBSTRING_INDEX(Name, ' ', -1) as lname FROM mytable;
Here is the split function I use:
--
-- split function
-- s : string to split
-- del : delimiter
-- i : index requested
--
DROP FUNCTION IF EXISTS SPLIT_STRING;
DELIMITER $
CREATE FUNCTION
SPLIT_STRING ( s VARCHAR(1024) , del CHAR(1) , i INT)
RETURNS VARCHAR(1024)
DETERMINISTIC -- always returns same results for same input parameters
BEGIN
DECLARE n INT ;
-- get max number of items
SET n = LENGTH(s) - LENGTH(REPLACE(s, del, '')) + 1;
IF i > n THEN
RETURN NULL ;
ELSE
RETURN SUBSTRING_INDEX(SUBSTRING_INDEX(s, del, i) , del , -1 ) ;
END IF;
END
$
DELIMITER ;
SET #agg = "G1;G2;G3;G4;" ;
SELECT SPLIT_STRING(#agg,';',1) ;
SELECT SPLIT_STRING(#agg,';',2) ;
SELECT SPLIT_STRING(#agg,';',3) ;
SELECT SPLIT_STRING(#agg,';',4) ;
SELECT SPLIT_STRING(#agg,';',5) ;
SELECT SPLIT_STRING(#agg,';',6) ;
select (case when locate('(', LocationName) = 0
then
horse_name
else
left(LocationName, locate('(', LocationName) - 1)
end) as Country
from tblcountry;
concat(upper(substring(substring_index(NAME, ' ', 1) FROM 1 FOR 1)), lower(substring(substring_index(NAME, ' ', 1) FROM 2 FOR length(substring_index(NAME, ' ', 1))))) AS fname,
CASE
WHEN length(substring_index(substring_index(NAME, ' ', 2), ' ', -1)) > 2 THEN
concat(upper(substring(substring_index(substring_index(NAME, ' ', 2), ' ', -1) FROM 1 FOR 1)), lower(substring(substring_index(substring_index(f.nome, ' ', 2), ' ', -1) FROM 2 FOR length(substring_index(substring_index(f.nome, ' ', 2), ' ', -1)))))
ELSE
CASE
WHEN length(substring_index(substring_index(f.nome, ' ', 3), ' ', -1)) > 2 THEN
concat(upper(substring(substring_index(substring_index(f.nome, ' ', 3), ' ', -1) FROM 1 FOR 1)), lower(substring(substring_index(substring_index(f.nome, ' ', 3), ' ', -1) FROM 2 FOR length(substring_index(substring_index(f.nome, ' ', 3), ' ', -1)))))
END
END
AS mname
To get the rest of the string after the second instance of the space delimiter
SELECT
SUBSTRING_INDEX(SUBSTRING_INDEX('Sachin ramesh tendulkar', ' ', 1), ' ', -1) AS first_name,
SUBSTRING_INDEX(SUBSTRING_INDEX('Sachin ramesh tendulkar', ' ', 2), ' ', -1)
AS middle_name,
SUBSTRING('Sachin ramesh tendulkar',LENGTH(SUBSTRING_INDEX('Sachin ramesh tendulkar', ' ', 2))+1) AS last_name
SELECT
p.fullname AS 'Fullname',
SUBSTRING_INDEX(p.fullname, ' ', 1) AS 'Firstname',
SUBSTRING(p.fullname, LOCATE(' ',p.fullname),
(LENGTH(p.fullname) - (LENGTH(SUBSTRING_INDEX(p.fullname, ' ', 1)) + LENGTH(SUBSTRING_INDEX(p.fullname, ' ', -1))))
) AS 'Middlename',
SUBSTRING_INDEX(p.fullname, ' ', -1) AS 'Lastname',
(LENGTH(p.fullname) - LENGTH(REPLACE(p.fullname, ' ', '')) + 1) AS 'Name Qt'
FROM people AS p
LIMIT 100;
Explaining:
Find firstname and lastname are easy, you have just to use SUBSTR_INDEX function
Magic happens in middlename, where was used SUBSTR with Locate to find the first space position and LENGTH of fullname - (LENGTH firstname + LENGTH lastname) to get all the middlename.
Note that LENGTH of firstname and lastname were calculated using SUBSTR_INDEX
You could use the common_schema and use the tokenize function. For more information about this, follow the links. Your code the would end up like:
call tokenize(name, ' ');
However, be aware that a space is not a reliable separator for first and last name. E.g. In Spain it is common to have two last names.
CREATE DEFINER=`root`#`localhost` FUNCTION `getNameInitials`(`fullname` VARCHAR(500), `separator` VARCHAR(1)) RETURNS varchar(70) CHARSET latin1
DETERMINISTIC
BEGIN
DECLARE `result` VARCHAR(500) DEFAULT '';
DECLARE `position` TINYINT;
SET `fullname` = TRIM(`fullname`);
SET `position` = LOCATE(`separator`, `fullname`);
IF NOT `position`
THEN RETURN LEFT(`fullname`,1);
END IF;
SET `fullname` = CONCAT(`fullname`,`separator`);
SET `result` = LEFT(`fullname`, 1);
cycle: LOOP
SET `fullname` = SUBSTR(`fullname`, `position` + 1);
SET `position` = LOCATE(`separator`, `fullname`);
IF NOT `position` OR NOT LENGTH(`fullname`)
THEN LEAVE cycle;
END IF;
SET `result` = CONCAT(`result`,LEFT(`fullname`, 1));
-- SET `result` = CONCAT_WS(`separator`, `result`, `buffer`);
END LOOP cycle;
RETURN upper(`result`);
END
1.Execute this function in mysql.
2.this will create a function. Now you can use this function anywhere you want.
SELECT `getNameInitials`('Kaleem Ul Hassan', ' ') AS `NameInitials`;
3. The above getNameInitails first parameter is string you want to filter and second is the spectator character on which you want to separate you string.
4. In above example 'Kaleem Ul Hassan' is name and i want to get initials and my separator is space ' '.
We have stored the value of course Name and chapter name in single column ChapterName.
Value stored like : " JAVA : Polymorphism "
you need to retrieve CourseName : JAVA and ChapterName : Polymorphism
Below is the SQL select query to retrieve .
SELECT
SUBSTRING_INDEX(SUBSTRING_INDEX(ChapterName, ' ', 1), ' ', -1) AS
CourseName,
REPLACE(TRIM(SUBSTR(ChapterName, LOCATE(':', ChapterName)) ),':','') AS
ChapterName
FROM Courses where `id`=1;
Please let me know if any question on this.
Combined a few answers here to create a SP that returns the parts of the string.
drop procedure if exists SplitStr;
DELIMITER ;;
CREATE PROCEDURE `SplitStr`(IN Str VARCHAR(2000), IN Delim VARCHAR(1))
BEGIN
DECLARE inipos INT;
DECLARE endpos INT;
DECLARE maxlen INT;
DECLARE fullstr VARCHAR(2000);
DECLARE item VARCHAR(2000);
create temporary table if not exists tb_split
(
item varchar(2000)
);
SET inipos = 1;
SET fullstr = CONCAT(Str, delim);
SET maxlen = LENGTH(fullstr);
REPEAT
SET endpos = LOCATE(delim, fullstr, inipos);
SET item = SUBSTR(fullstr, inipos, endpos - inipos);
IF item <> '' AND item IS NOT NULL THEN
insert into tb_split values(item);
END IF;
SET inipos = endpos + 1;
UNTIL inipos >= maxlen END REPEAT;
SELECT * from tb_split;
drop table tb_split;
END;;
DELIMITER ;
To get the rest of the string after the second instance of the space delimiter:
SELECT SUBSTRING_INDEX(SUBSTRING_INDEX(MsgRest, ' ', 1), ' ', -1) AS EMailID
, SUBSTRING_INDEX(SUBSTRING_INDEX(MsgRest, ' ', 2), ' ', -1) AS DOB
, IF(
LOCATE(' ', `MsgRest`) > 0,
TRIM(SUBSTRING(SUBSTRING(`MsgRest`, LOCATE(' ', `MsgRest`) +1),
LOCATE(' ', SUBSTRING(`MsgRest`, LOCATE(' ', `MsgRest`) +1)) +1)),
NULL
) AS Person
FROM inbox
DELIMITER $$
DROP FUNCTION IF EXISTS `split_name`$$
CREATE FUNCTION split_name (p_fullname TEXT, p_part INTEGER)
RETURNS TEXT
READS SQL DATA
BEGIN
DECLARE v_words INT UNSIGNED;
DECLARE v_name TEXT;
SET p_fullname=RTRIM(LTRIM(p_fullname));
SET v_words=(SELECT SUM(LENGTH(p_fullname) - LENGTH(REPLACE(p_fullname, ' ', ''))+1));
IF v_words=1 THEN
IF p_part=1 THEN
SET v_name=p_fullname;
ELSEIF p_part=2 THEN
SET v_name=NULL;
ELSEIF p_part=3 THEN
SET v_name=NULL;
ELSE
SET v_name=NULL;
END IF;
ELSEIF v_words=2 THEN
IF p_part=1 THEN
SET v_name=SUBSTRING(p_fullname, 1, LOCATE(' ', p_fullname) - 1);
ELSEIF p_part=2 THEN
SET v_name=SUBSTRING(p_fullname, LOCATE(' ', p_fullname) + 1);
ELSEIF p_part=3 THEN
SET v_name=NULL;
ELSE
SET v_name=NULL;
END IF;
ELSEIF v_words=3 THEN
IF p_part=1 THEN
SET v_name=SUBSTRING(p_fullname, 1, LOCATE(' ', p_fullname) - 1);
ELSEIF p_part=2 THEN
SET p_fullname=SUBSTRING(p_fullname, LOCATE(' ', p_fullname) + 1);
SET v_name=SUBSTRING(p_fullname, 1, LOCATE(' ', p_fullname) - 1);
ELSEIF p_part=3 THEN
SET p_fullname=REVERSE (SUBSTRING(p_fullname, LOCATE(' ', p_fullname) + 1));
SET p_fullname=SUBSTRING(p_fullname, 1, LOCATE(' ', p_fullname) - 1);
SET v_name=REVERSE(p_fullname);
ELSE
SET v_name=NULL;
END IF;
ELSEIF v_words>3 THEN
IF p_part=1 THEN
SET v_name=SUBSTRING(p_fullname, 1, LOCATE(' ', p_fullname) - 1);
ELSEIF p_part=2 THEN
SET p_fullname=REVERSE(SUBSTRING(p_fullname, LOCATE(' ', p_fullname) + 1));
SET p_fullname=SUBSTRING(p_fullname, LOCATE(' ', p_fullname,SUBSTRING_INDEX(p_fullname,' ',1)+1) + 1);
SET v_name=REVERSE(p_fullname);
ELSEIF p_part=3 THEN
SET p_fullname=REVERSE (SUBSTRING(p_fullname, LOCATE(' ', p_fullname) + 1));
SET p_fullname=SUBSTRING(p_fullname, 1, LOCATE(' ', p_fullname) - 1);
SET v_name=REVERSE(p_fullname);
ELSE
SET v_name=NULL;
END IF;
ELSE
SET v_name=NULL;
END IF;
RETURN v_name;
END;
SELECT split_name('Md. Obaidul Haque Sarker',1) AS first_name,
split_name('Md. Obaidul Haque Sarker',2) AS middle_name,
split_name('Md. Obaidul Haque Sarker',3) AS last_name
First Create Procedure as Below:
CREATE DEFINER=`root`#`%` PROCEDURE `sp_split`(str nvarchar(6500), dilimiter varchar(15), tmp_name varchar(50))
BEGIN
declare end_index int;
declare part nvarchar(6500);
declare remain_len int;
set end_index = INSTR(str, dilimiter);
while(end_index != 0) do
/* Split a part */
set part = SUBSTRING(str, 1, end_index - 1);
/* insert record to temp table */
call `sp_split_insert`(tmp_name, part);
set remain_len = length(str) - end_index;
set str = substring(str, end_index + 1, remain_len);
set end_index = INSTR(str, dilimiter);
end while;
if(length(str) > 0) then
/* insert record to temp table */
call `sp_split_insert`(tmp_name, str);
end if;
END
After that create procedure as below:
CREATE DEFINER=`root`#`%` PROCEDURE `sp_split_insert`(tb_name varchar(255), tb_value nvarchar(6500))
BEGIN
SET #sql = CONCAT('Insert Into ', tb_name,'(item) Values(?)');
PREPARE s1 from #sql;
SET #paramA = tb_value;
EXECUTE s1 USING #paramA;
END
How call test
CREATE DEFINER=`root`#`%` PROCEDURE `test_split`(test_text nvarchar(255))
BEGIN
create temporary table if not exists tb_search
(
item nvarchar(6500)
);
call sp_split(test_split, ',', 'tb_search');
select * from tb_search where length(trim(item)) > 0;
drop table tb_search;
END
call `test_split`('Apple,Banana,Mengo');
Based on previous answers and do some modifications...
note:
p_delimiter has to be VARCHAR(1) couse CHAR(1) if is ' ' (space) gives '' (removes space and returns empty string)
Instead use of LENGTH I prefer CHAR_LENGTH which is safe for multibyte characters like UTF
DROP FUNCTION IF EXISTS FN_SPLIT_STR;
DELIMITER ;;
CREATE FUNCTION FN_SPLIT_STR(
p_input VARCHAR(2000), p_delimiter VARCHAR(1), p_position INT
)
RETURNS VARCHAR(2000)
DETERMINISTIC
BEGIN
DECLARE chunks INT;
SET chunks := CHAR_LENGTH(p_input) - CHAR_LENGTH(REPLACE(p_input, p_delimiter, '')) + 1;
IF p_position > chunks THEN
RETURN NULL;
END IF;
RETURN SUBSTRING_INDEX(SUBSTRING_INDEX(p_input, p_delimiter, p_position), p_delimiter, -1);
END;;
DELIMITER ;
SELECT "SUBSTRING_INDEX(name, ' ', 1) as first_name", "TRIM(REPLACE(name, SUBSTRING_INDEX(name, ' ', 1), '')) as last_name" FROM tbl;

MySQL : how to remove double or more spaces from a string?

I couldn't find this question for MySQL so here it is:
I need to trim all double or more spaces in a string to 1 single space.
For example:
"The Quick Brown Fox"
should be :
"The Quick Brown Fox"
The function REPLACE(str, " ", " ") only removes double spaces, but leaves multiples spaces when there are more...
Here's an old trick that does not require regular expressions or complicated functions.
You can use the replace function 3 times to handle any number of spaces, like so:
REPLACE('This is my long string',' ','<>')
becomes:
This<>is<><><><>my<><><>long<><><><>string
Then you replace all occurrences of '><' with an empty string '' by wrapping it in another replace:
REPLACE(
REPLACE('This is my long string',' ','<>'),
'><',''
)
This<>is<>my<>long<>string
Then finally one last replace converts the '<>' back to a single space
REPLACE(
REPLACE(
REPLACE('This is my long string',
' ','<>'),
'><',''),
'<>',' ')
This is my long string
This example was created in MYSQL (put a SELECT in front) but works in many languages.
Note that you only ever need the 3 replace functions to handle any number of characters to be replaced.
The shortest and, surprisingly, the fastest solution:
CREATE FUNCTION clean_spaces(str VARCHAR(255)) RETURNS VARCHAR(255)
BEGIN
while instr(str, ' ') > 0 do
set str := replace(str, ' ', ' ');
end while;
return trim(str);
END
I know this question is tagged with mysql, but if you're fortunate enough to use MariaDB you can do this more easily:
SELECT REGEXP_REPLACE(column, '[[:space:]]+', ' ');
DELIMITER //
DROP FUNCTION IF EXISTS DELETE_DOUBLE_SPACES//
CREATE FUNCTION DELETE_DOUBLE_SPACES ( title VARCHAR(250) )
RETURNS VARCHAR(250) DETERMINISTIC
BEGIN
DECLARE result VARCHAR(250);
SET result = REPLACE( title, ' ', ' ' );
WHILE (result <> title) DO
SET title = result;
SET result = REPLACE( title, ' ', ' ' );
END WHILE;
RETURN result;
END//
DELIMITER ;
SELECT DELETE_DOUBLE_SPACES('a b');
This solution isn't very elegant but since you don't have any other option:
UPDATE t1 set str = REPLACE( REPLACE( REPLACE( str, " ", " " ), " ", " " ), " ", " " );
After searching I end up writing a function i.e
drop function if exists trim_spaces;
delimiter $$
CREATE DEFINER=`root`#`localhost` FUNCTION `trim_spaces`(`dirty_string` text, `trimChar` varchar(1))
RETURNS text
LANGUAGE SQL
NOT DETERMINISTIC
CONTAINS SQL
SQL SECURITY DEFINER
COMMENT ''
BEGIN
declare cnt,len int(11) ;
declare clean_string text;
declare chr,lst varchar(1);
set len=length(dirty_string);
set cnt=1;
set clean_string='';
while cnt <= len do
set chr=right(left(dirty_string,cnt),1);
if chr <> trimChar OR (chr=trimChar AND lst <> trimChar ) then
set clean_string =concat(clean_string,chr);
set lst=chr;
end if;
set cnt=cnt+1;
end while;
return clean_string;
END
$$
delimiter ;
USAGE:
set #str='------apple--------banana-------------orange---' ;
select trim_spaces( #str,'-')
output: apple-banana-orange-
parameter trimChar to function could by any character that is repeating and you want to remove .
Note it will keep first character in repeating set
cheers :)
For MySQL 8+, you can use REGEXP_REPLACE function:
UPDATE `your_table`
SET `col_to_change`= REGEXP_REPLACE(col_to_change, '[[:space:]]+', ' ');
This is slightly general solution: from
http://www.sqlteam.com/forums/topic.asp?TOPIC_ID=56195&whichpage=1
create table t (s sysname)
insert into t select 'The Quick Brown Fox'
-- convert tabs to spaces
update t set s = replace(s, ' ',' ')
where charindex(' ', s) > 0
-- now do the work.
while 1=1
begin
update t
set s = substring(s, 1, charindex(' ', s, 1)-1) + ' ' + ltrim(substring(s,charindex(' ', s, 1), 8000))
where charindex(' ', s, 1) > 0
if ##rowcount = 0
break
end
select s
from t
If the string that you want to convert consists of only alphabets and multiple number of spaces [A-Za-z ]* then the following function will work. I found out a pattern when such strings are converted to hex. Based on that my solution follows. Not so elegant, but it doesn't require any procedures.
unhex(
replace(
replace(
replace(
replace(
replace(
replace(
hex(str)
,204,1014)
,205,1015)
,206,1016)
,207,1017)
,20,'')
,101,20)
)
If you are using php....
try{
$con = new PDO ("mysql:host=localhost;dbname=dbasename","root","");
}
catch(PDOException $e){
echo "error".$e-getMessage();
}
$select = $con->prepare("SELECT * FROM table");
$select->setFetchMode(PDO::FETCH_ASSOC);
$select->execute();
while($data=$select->fetch()){
$id = $data['id'];
$column = $data['column'];
$column = trim(preg_replace('/\s+/',' ', $column)); // remove all extra space
$update = $con->prepare("UPDATE table SET column=:column WHERE id='$id'");
$update->bindParam(':column', $column );
$update->execute();
// echo $column."<br>";
}
Follow my generic function made for MySQL 5.6. My intention was to use regular expression to identify the spaces, CR and LF, however, it is not supported by this version of mysql. So, I had to loop through the string looking for the characters.
CREATE DEFINER=`db_xpto`#`%` FUNCTION `trim_spaces_and_crlf_entire_string`(`StringSuja` text) RETURNS text CHARSET utf8 COLLATE utf8_unicode_ci
DETERMINISTIC
BEGIN
DECLARE StringLimpa TEXT;
DECLARE CaracterAtual, CaracterAnterior TEXT;
DECLARE Contador, TamanhoStringSuja INT;
SET StringLimpa = '';
SET CaracterAtual = '';
SET CaracterAnterior = '';
SET TamanhoStringSuja = LENGTH(StringSuja);
SET Contador = 1;
WHILE Contador <= TamanhoStringSuja DO
SET CaracterAtual = SUBSTRING(StringSuja, Contador, 1);
IF ( CaracterAtual = ' ' AND CaracterAnterior = ' ' ) OR CaracterAtual = '\n' OR CaracterAtual = '\r' THEN
/* DO NOTHING */
SET Contador = Contador;
/* TORNA OS ESPAÇOS DUPLICADOS, CR, LF VISUALIZÁVEIS NO RESULTADO (DEBUG)
IF ( CaracterAtual = ' ' ) THEN SET StringLimpa = CONCAT(StringLimpa, '*');END IF;
IF ( CaracterAtual = '\n' ) THEN SET StringLimpa = CONCAT(StringLimpa, '\\N');END IF;
IF ( CaracterAtual = '\r' ) THEN SET StringLimpa = CONCAT(StringLimpa, '\\R');END IF;
*/
ELSE
/* COPIA CARACTER ATUAL PARA A STRING A FIM DE RECONSTRUÍ-LA SEM OS ESPAÇOS DUPLICADOS */
SET StringLimpa = CONCAT(StringLimpa, CaracterAtual);
/*SET StringLimpa = CONCAT(StringLimpa, Contador, CaracterAtual);*/
SET CaracterAnterior = CaracterAtual;
END IF;
SET Contador = Contador + 1;
END WHILE;
RETURN StringLimpa;
END
In MySQL 8+:
SELECT REGEXP_REPLACE(str, '\\s+', ' ');
you can try removing more tan one space with regex
SELECT REGEXP_REPLACE('This is my long string',' +', ' ');
the result would be this: "This is my long string"