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