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 strongm on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

Substring from right? 1

Status
Not open for further replies.

DugsDMan

Programmer
Mar 19, 2002
85
US
Is there a keyword I can use to grab the last n characters in a field? I can do it using substring and octet length and such, but figured there has to be a better way.

Anyone know?

Thanks!
 
How about this to get the last 3 characters from a column

SELECT SUBSTRING(TRIM(column) FROM CHARACTER_LENGTH(TRIM(column)) -2 FOR 3) from Table

If column is CHAR(10) and contains "WEST "
TRIM removes trailing spaces
CHARACTER_LENGTH returns 4
subtract 2 from CHARACTER_LENGTH = 2
SUBSTRING FROM 2 FOR 3 gives "EST"
 
Thanks jgerstb. I knew it could be done with lengths and such, just figured there'd be some keyword. In programming, all language I've used have some kind of left, right, mid functionality. But, I've never had to try it in SQL. Just curious if one existed.

Thanks!
 
the right way is :
substr ( string,char(string)-n,n+1)
 
I tried that and it just gives me the whole field.

Here's what I'm trying to do. I have a field that I need to get codes from. The source data comes from multiple sources. The field is defined as char(5), but can be 3-5 digits. All I need are the last 4 digits (if there are 4 there). If it's 3, I want all 3. If it's 4, I want all 4. If it's 5, then I only want the 4 on the right.

Ex:
Column
123
4567
12345

I would want to get this back:
123
4567
2345

Do you know how I can do this?

Thanks!
 
Go idea Dieter! I'll try that when I can log on again. Their doing maintenance now, so I can't check it. Seems like it should work just fine though.

Thanks!
 
Guess that should have been "Good idea" :)

I tried it on our dev system and it worked great.

Thanks Dieter!!
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top