Reputation: 27
I need to extract or just retain certain characters from a varying string using SQL in Oracle. I used the SUBSTR function but that does not work for all the cases.
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. I have given all kind of examples I have. Thanks
Upvotes: 1
Views: 98
Reputation: 2679
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:
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.
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. You could use 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).
SELECT REGEXP_SUBSTR('B2B_BID-SKU340020201','SKU[0-9]+') FROM DUAL;
Upvotes: 1
Reputation: 1269803
You can get what you want with substr()
, instr()
, and 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
:
select substr(val, instr(val, 'SKU'))
from (select 'B2B_BID-XSKU957109' as val from dual) t
Here is a little SQL Fiddle.
Upvotes: 2