I have a Char(15)
field, in this field I have the data below:
94342KMR
947JCP
7048MYC
I need to break down this, I need to get the last RIGHT 3 characters and I need to get whatever is to the LEFT. My issue is that the code on the LEFT is not always the same length as you can see.
How can I accomplish this in SQL?
Thank you
The LEFT function in Excel is a type of text function in Excel that gives the number of characters from the start of the string, from left to right. So, for example, if we use this function as =LEFT ( “ANAND”,2) this will give us AN as a result.
LEFT returns the first character or characters in a text string, based on the number of characters you specify. LEFTB returns the first character or characters in a text string, based on the number of bytes you specify. Important: These functions may not be available in all languages.
SELECT RIGHT(RTRIM(column), 3),
LEFT(column, LEN(column) - 3)
FROM table
Use RIGHT
w/ RTRIM
(to avoid complications with a fixed-length column), and LEFT
coupled with LEN
(to only grab what you need, exempt of the last 3 characters).
if there's ever a situation where the length is <= 3, then you're probably going to have to use a CASE
statement so the LEFT
call doesn't get greedy.
You can use RTRIM
or cast your value to VARCHAR
:
SELECT RIGHT(RTRIM(Field),3), LEFT(Field,LEN(Field)-3)
Or
SELECT RIGHT(CAST(Field AS VARCHAR(15)),3), LEFT(Field,LEN(Field)-3)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With