7

How do I get a substring from this example value:

 john.abc_1234

I want it to return john.abc.So basically we need to remove all the information after _.

More examples: 1234_abc

Sathyajith Bhat
  • 21,321
  • 22
  • 95
  • 134
sandy
  • 181
  • 1
  • 2
  • 9
  • 3
    Does this answer your question? [How to remove part of the string in oracle](https://stackoverflow.com/questions/19852516/how-to-remove-part-of-the-string-in-oracle) – Himanshu Dec 14 '19 at 09:04

4 Answers4

25

You can use SUBSTR and INSTR:

select substr('john.abc_1234', 1, instr('john.abc_1234', '_') -1)
from dual

Warning: This is only guaranteed to work if your string actually has an underscore in it

Update

Additionally, if you are running from Oracle 10g on, you could take the Regex path, which would more powerfully handle exceptions.

Here are some links on how to do it in Oracle:

Adriano Carneiro
  • 57,693
  • 12
  • 90
  • 123
2

You can use via a simple combination of substr(..) and instr(...) to find the string which is free from underscore special charecter. Also in order to only select _ containing strings you can make use of additional where clause as below

       select substr('john.abc_1234', 1, 
       instr('john.abc_1234', '_') -1)
      from dual where 
      instr('john.abc_1234', '_')>0
Himanshu
  • 3,830
  • 2
  • 10
  • 29
1

You can use this monstrosity, when you're not sure if all your values contain the character you want to cut off your string at.

SELECT
    (CASE WHEN INSTR(field, '_') > 0
        THEN substr(field, 1, instr(field, '_') -1)
        ELSE field
    END) AS field
FROM
    dual
sparklos
  • 452
  • 4
  • 10
-1

This guy figured it out! http://programcsharp.com/blog/post/strip-non-numeric-characters-from-a-string-in-sql-server

SELECT
    (SELECT CAST(CAST((
        SELECT SUBSTRING(FieldToStrip, Number, 1)
        FROM master..spt_values
        WHERE Type='p' AND Number <= LEN(FieldToStrip) AND
            SUBSTRING(FieldToStrip, Number, 1) LIKE '[0-9]' FOR XML Path(''))
    AS xml) AS varchar(MAX)))
FROM
    SourceTable
lolol
  • 4,287
  • 3
  • 35
  • 54