3

I am trying to only return the second to last character from a string using MS SQL.

I've tried using MID and Substring but the length of the string isn't always the same for the column I am trying to return, So I can't do it that way.

So say I am returning the codes of something:

Code
'1234'

I want to just return '3' from that code.

How can I do this? Cheers in advance :)

1
  • 1
    For sure you can use substring on variable column lengths Commented Oct 20, 2014 at 11:36

2 Answers 2

5

Use SUBSTRING and LEN. LEN gives you the length of the string, then subtract 1 to get the previous char:

SELECT SUBSTRING(Code, LEN(Code)-1,1)
Sign up to request clarification or add additional context in comments.

1 Comment

Thanks so much new to this and this problem has been bugging me for hours!!
2

How about

select left(right(code, 2), 1) from MyTable;

You might need to validate that the string actually has at least 2 chars, however.

SqlFiddle here

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.