tags:

views:

49

answers:

2

I am writing a query in Oracle.

I want to get a string from the right hand side but the string length is dynamic.

Ex:

299123456789

I want to get 123456789

substr(PHONE_NUMBERS,-X,Y)

X is different for each record.

I tried this:

substr(PHONE_NUMBERS,-length(PHONE_NUMBERS),Y)

and it didn't work..

How can I write this query?

Thanks.

+1  A: 
SQL> select substr('123456',-1,6) from dual;

S
-
6

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

SUBSTR
------
123456

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

S
-

If you watch above statements, 3 query gives null value as -7 > length('123456').

So check the length of CONT_PHONE_NUMBERS and PHONE_NUMBERS

Hope this helps you

Bharat
I dont know the length of PHONE_NUMBERS. Each record has different length.
Jack
@Jack, Bharat's answer will work regardless of the length of the data. A negative argument for the second parameter of SUBSTR counts from the end of the string.
Jeffrey Kemp
@Jeffrey I know it, but length of the string is different for each record, so I have to use length function or something like that for the negative argument
Jack
@Jack: Can you post your query and the output of that query
Bharat
ok. I solved. Solution: substr(PHONE_NUMBERS,length(PHONE_NUMBERS)-9,9)
Jack
A: 
SQL> select substr('999123456789', greatest (-9, -length('999123456789')), 9) as value from dual;

VALUE
---------
123456789

SQL> select substr('12345', greatest (-9,  -length('12345')), 9) as value from dual;

VALUE
----
12345

The call to greatest (-9, -length(string)) limits the starting offset either 9 characters left of the end or the beginning of the string.

Adam Musch
greatest function returns greatest number.. there is no relevance in this case..
Jack
As per Adam's answer, the greatest prevents the negative offset being longer than the string - i.e. substr('this string',-9) will give the 9 rightmost characters of the string BUT not if the string is SMALLER than 9 characters. The Greatest of (-9,-6) is -6. The greatest ensures it cannot offset longer than the length of the string.
JulesLt
Couldn't edit so a second comment.This is the right answer. The greatest prevents the negative offset being longer than the string - i.e. substr('0123456789',-9) will give the 9 rightmost characters of the string. substr('0123456789',-12) gives NULL. The offset cannot be LONGER than the string. The GREATEST ensures this : GREATEST( -LENGTH('0123456789'),-12) is GREATEST(-10,-12) is -10. It ensures the offset is not longer than the string, which the first answer will not do. The first answer will work so long as string is always longer than X.
JulesLt
Jack - the greatest () of two negative numbers is the least negative of the two. In the second of the two examples, greatest (-9, -5) evaluates to -5.
Adam Musch