Question

I need to search for and display a part of a string field. The string value from record to record may be different. For example:


Record #1

String Value:

IA_UnsafesclchOffense0IA_ReceivedEdServDuringExp0IA_SeriousBodilyInjuryN

Record #2

String Value:

 IA_ReasonForRemovalTIA_Beh_Inc_Num1392137419IA_RemovalTypeNIA_UnsafesclchOffense0IA_ReceivedEdServDuringExp0IA_SeriousBodilyInjuryN

Record #3

String Value:

IA_UnsafesclchOffense0IA_RemovalTypeSIA_ReasonForRemovalPIA_ReceivedEdServDuringExp0IA_Beh_Inc_Num1396032888IA_SeriousBodilyInjuryN

In each case, I need to search for IA_Beh_Inc_Num. Assuming it's found, and IF it's followed by numeric data, I want to RETURN the numeric portion of that data. The numeric data, when present, will always be 10 characters. In other words, record #1 should return no value, record #2 should return 1392137419 and record #3 should return 1396032888

Is there a way to do this within a select statement without having to write a full function with PL/SQL?

Was it helpful?

Solution 2

This would work:

SELECT 
CASE WHEN instr(value, 'IA_Beh_Inc_Num') > 0
     THEN substr(substr(value, instr(value, 'IA_Beh_Inc_Num'), 25),15,10)
     ELSE 'not found'
END AS result
FROM example

See this SQL Fiddle.

OTHER TIPS

This should be easy with a Regular Expression: find a search string and check if it's followed by 10 digits:

REGEXP_SUBSTR(col, '(?<=IA_Beh_Inc_Num)([0-9]{10})')

but Oracle doesn't seem to support RegEx lookahead, so it's bit more complicated:

REGEXP_SUBSTR(value, '(IA_Beh_Inc_Num)([0-9]{10})',1,1,'i',2)

Remarks: the search is case-insensitive and if there are less than 10 digits NULL will be returned.

Angelo's answer is correct for Oracle, as the question asked. For those from SQL Server coming across this, the below would work:

SELECT CASE 
        WHEN CHARINDEX('IA_Beh_Inc_Num', StringColumn) = 0
            THEN NULL
        ELSE SUBSTRING(StringColumn, CHARINDEX('IA_Beh_Inc_Num', StringColumn) + LEN('IA_Beh_Inc_Num'), 10)
        END AS unix_time
    ,*
FROM MyTable

EDIT:

Modified query to select all rows. The query prints "NOT A TIMESTAMP" if IA_Beh_Inc_Num does not exist within the string or if it is not followed by 10 numbers.

SELECT
  DECODE
    (
    REGEXP_INSTR (value, 'IA_Beh_Inc_Num[0-9]{10}'), 
    0, 
    'NOT A TIMESTAMP', 
    SUBSTR(value, INSTR(value, 'IA_Beh_Inc_Num')+14, 10)
    ) timestamp
FROM example;

SQL Fiddle

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top