Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations Chris Miller on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

Reading from back end of string using SUBSTR 3

Status
Not open for further replies.

CIMTEET

Programmer
Jun 25, 2001
182
US
SUBSTR(string,<i>,<j>) i is start point joint is length from start point.

I have been reading on this and SUBSTR is supposed read from back of string when the <j> portion is negative as long as the <i> portion is not 0 or negative. My code:

set serveroutput on size 2000
DECLARE
s1 VARCHAR2(2000);
BEGIN
s1:='123456789';
DBMS_OUTPUT.PUT_LINE('name '||substr(s1,1,-3));
END;

The output I get is ::
name

When I expect ::

name 789

I can program around this from the front, I just don't like it when things don't work how they are explained. Am I wrong or have misinterpreted the directions? I don't think I have but it could be a possiblity. Please help.

Thanks
 
you dont need the <j> value, just make <i> a negative

eg
select substr('Hello',-1) from dual
will give you 'o'
 
To clarify Bloke152's advice, the minus sign needs to go on the <i> value, but in your specific example you also need the <j> value to get the last three characters of the string.

Code:
SQL> select 'name '||substr('123456789', -3, 3) from dual;

'NAME'||
--------
name 789

The parameters of -3 and 3 mean start three characters from the right side of the string (-3) and take a substring three characters long (3).
 
Well, I see I should test things before posting. I thought omitting the <j> value would cause it to default to a substring of length 1, but it actually seems to take the entire end of the string. You only need <j>, I guess, if you don't want all of the characters at the end of the string.

Have a star, Bloke152, for teaching this old dog a new trick.
 
Have a star Karluk for being an old dog that is humble enough to learn a new trick!
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top