简体   繁体   English

在SQL中提取特定字符串

[英]Extracting Particular String in SQL

I need to extract or just retain certain characters from a varying string using SQL in Oracle. 我需要使用Oracle中的SQL从不同的字符串中提取或保留某些字符。 I used the SUBSTR function but that does not work for all the cases. 我使用了SUBSTR功能,但这并不适用于所有情况。

Example: Values are like this: 示例:值如下所示:

B2B_BID-XSKU957109
B2B_BID-SKU340535
B2B-SKU342345
B2B_BID-SKU340020201

Results I want: 结果我想:

SKU957109
SKU340535
SKU342345
SKU340020201

So its just not the last 10 characters but I want only the part which has the string 'SKU' and the number following it. 所以它只是不是最后10个字符,但我只想要有字符串'SKU'的部分和跟随它的数字。 I have given all kind of examples I have. 我已经举了各种例子。 Thanks 谢谢

You can get what you want with substr() , instr() , and reverse() : 你可以通过substr()instr()reverse()得到你想要的东西:

select substr(val, 1-instr(reverse(val), '-'))
from (select 'B2B_BID-XSKU957109' as val from dual) t

The above seemed to answer a slightly different question about getting the stuff after the last - . 上面似乎回答了关于在最后一次之后得到这些东西的一个稍微不同的问题- To get the stuff with the last SKU : 要获得最后一个SKU的东西:

select substr(val, instr(val, 'SKU'))
from (select 'B2B_BID-XSKU957109' as val from dual) t

Here is a little SQL Fiddle. 是一个小小的SQL小提琴。

Fixed token 固定令牌

If the token you're trying to extract is fixed length and always at the same place, you can use the substr function with negative index: 如果您尝试提取的令牌是固定长度并且始终位于同一位置,则可以使用带负索引的substr函数:

select substr('123456',-1,6) from dual;

S
-
6

select substr('123456',-6,6) from dual;

SUBSTR
------
123456

In your case it seems the token has variable length, though. 在你的情况下,似乎令牌具有可变长度。

Variable Length Token 可变长度令牌

If the string you're trying to extract is not fix, you can't do it with traditional SQL or with the simple substr function. 如果您尝试提取的字符串未修复,则无法使用传统SQL或简单的substr函数执行此操作。 You could use regexp_substr . 你可以使用regexp_substr In this latter case, except if you really need for some exotic reason to treat your string in Oracle, I'd suggest you to do that in the application instead (or to double check carefully the regexp hit on Oracle performances). 在后一种情况下,除非你真的需要一些异乎寻常的理由在Oracle中处理你的字符串,我建议你在应用程序中这样做(或仔细仔细检查regexp命中Oracle性能)。

Proposed Solution 提出的解决方案

SELECT REGEXP_SUBSTR('B2B_BID-SKU340020201','SKU[0-9]+') FROM DUAL;

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

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