如何用 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)

更新于:2019 年 7 月 30 日

769 次浏览

启动您的职业生涯

完成课程取得证书

马上开始
广告
© . All rights reserved.