如何在MySQL中从字符串中删除多个或更多空格?
您可以创建一个函数来删除字符串中的双重或更多空格。语法如下:
DELIMITER //
create function yourFunctionName(paramter1,...N) returns datatype;
begin
//your statement.
end;
//
DELIMITER ;
下面是如何创建一个函数:
mysql> delimiter //
mysql> create function function_DeleteSpaces(value varchar(200)) returns varchar(200)
-> begin
-> set value = trim(value);
-> while instr(value, ' ') > 0 do
-> set value = replace(value, ' ', ' ');
-> end while;
-> return value;
-> END;
-> //
Query OK, 0 rows affected (0.20 sec)
mysql> delimiter ;
现在可以使用select语句调用该函数。语法如下:
SELECT yourFunctionName();
使用select语句调用上述函数。上面的函数从字符串中删除空格:
mysql> select function_DeleteSpaces(' John Smith ');
以下是输出内容:
+--------------------------------------------------+
| function_DeleteSpaces(' John Smith ') |
+--------------------------------------------------+
| John Smith |
+--------------------------------------------------+
1 row in set (0.02 sec)
上述函数删除超过一个空格。让我们看一个带有函数参数的新值的另一个示例:
mysql> select function_DeleteSpaces(' John Smith 123 ');
以下是输出内容:
+---------------------------------------------------------+
| function_DeleteSpaces(' John Smith 123 ') |
+---------------------------------------------------------+
| John Smith 123 |
+---------------------------------------------------------+
1 row in set (0.00 sec)
阅读更多:MySQL 教程
极客教程