SQL删除最后一个字符,如果它是“ - ”

时间:2015-03-23 08:56:05

标签: mysql sql

我想删除连续的最后一个字符,但是如果最后一个字符是“ - ”。

例如,我的行看起来像这样:

hello-world

today-is-monday-

应该是这样的:

hello-world

today-is-monday

我如何在SQL中执行此操作?

3 个答案:

答案 0 :(得分:3)

您可以将trim()功能用作

mysql> select trim( trailing '-' from 'hello-');
+-----------------------------------+
| trim( trailing '-' from 'hello-') |
+-----------------------------------+
| hello                             |
+-----------------------------------+
1 row in set (0.00 sec)

mysql> select trim( trailing '-' from 'hello');
+----------------------------------+
| trim( trailing '-' from 'hello') |
+----------------------------------+
| hello                            |
+----------------------------------+
1 row in set (0.00 sec)

http://dev.mysql.com/doc/refman/5.0/en/string-functions.html#function_trim

因此,在查询中,用您的列名替换硬编码的hello-

答案 1 :(得分:0)

如果你的意思是更新表格,那么

UPDATE table 
SET field = SUBSTRING(field, 1, CHAR_LENGTH(field) - 1) 
WHERE field LIKE '%-'

如果您的意思是要编辑输出而不是表格中的数据,那么

SELECT CASE WHEN field LIKE '%-' 
THEN SUBSTRING(field, 1, CHAR_LENGTH(field) - 1) 
ELSE field 
END AS field

答案 2 :(得分:0)

跟随代码片段
声明

 a_msg VARCHAR2(4000);
 b_msg varchar2(100);
 BEGIN
 a_msg := '1,2,3,4,';
 b_msg := substr(a_msg,1,length(a_msg)-1);
 Dbms_Output.Put_line('b_msg:'||b_msg); 
 END ;

O / P:b_msg:1,2,3,4

相关问题