简体   繁体   English

在 SQL 中删除字符串的一部分

[英]Delete part of a string in SQL

I have a table with a field with this kind of entries:我有一个带有此类条目的字段的表:

"text text text"
"text text - Cap. 125"
"text - Cap. 1"

I need to cut " - Cap. (Number)" .我需要剪掉" - Cap. (Number)"

As you can see in some cases there's no "Cap."正如您在某些情况下所见,没有"Cap." and in other cases the number has more than 1 digit.在其他情况下,数字超过 1 位。

I tried to use REPLACE() and TRIM() , but REPLACE() only works for " - cap."我尝试使用REPLACE()TRIM() ,但REPLACE()仅适用于" - cap." but not for the numbers;但不是为了数字; and TRIM() cut a specific number of characters.TRIM()剪切特定数量的字符。

Also, I think I need something like WHERE field LIKE '% - CAP.%' to verify that I'm changing the right field, because not all the fields need to be changed.另外,我想我需要像WHERE field LIKE '% - CAP.%'来验证我正在更改正确的字段,因为并非所有字段都需要更改。

Any suggestions?有什么建议?

SELECT CASE
         WHEN myField RLIKE ' - Cap\\. [[:digit:]]{1,3}$' THEN
           LEFT(myField, 1
             + CHAR_LENGTH(myField)
             - CHAR_LENGTH(' - Cap. ')
             - LOCATE(REVERSE(' - Cap. '), REVERSE(myField))
           )
         ELSE myField
       END
FROM   myTable

See it on sqlfiddle .sqlfiddle查看

SELECT SUBSTRING_INDEX(column_name, 'Cap', 1) FROM table ; // for left
SELECT SUBSTRING_INDEX(column_name, 'Cap', -1) FROM table; // for right

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM