tags:

views:

141

answers:

1

I need to write a bit of SQL which parses the second word of any given string, or if there is no space, the entire string.

The logic is

'XXX YYYYY ZZZZZ' would return YYYY,

'XXX YYY' would return YYY and

'XXXXXX' would return XXXXXX.

Any suggestions? Is there a way of using SUBSTR and the 2 positions within the string? Rather an using the length.

Thanks very much

+3  A: 
case
    -- at least two words 
    when instr(c, ' ', 1, 1) > 0 then
        case
            -- at least three words 
            when instr(c, ' ', 1, 2) > 0 then
                -- return text between first and last space
                substr(
                    c
                ,   instr(c, ' ', 1, 1)+1                          
                ,   instr(c, ' ', 1, 2) - instr(c, ' ', 1, 1) - 1 
                )
            else
            -- return 2nd word (text after first space)
                substr(c, instr(c, ' ', 1, 1)+1)
        end
    -- one word, return it
    else c
end
Roland Bouman
Made use of the "instr(c, ' ', 1, 2) - instr(c, ' ', 1, 1) - 1" logic. Thanks agian.
fras85
It's a hassle, that's for sure. In MySQL, I'd probably use the `SUBSTRING_INDEX()` function which would make it considerably less messy.
Roland Bouman
It may be a hassle but in Oracle you put your logic in your own utility package and you will have it available at all times.
Rene
Rene, I agree, that would be a possibility. The exact implementation is something to consider though. Personally I am not a big fan of creating dependencies on utility packages, at least not when these aren't also part of the schema where you need them. Even then, it is a pity that string manipulation has to be so clunky. This is not just PL/SQL, same clunky string manipulation functions exist in other SQL dialects.
Roland Bouman