Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

SQL Query/function to remove alphabets only from end

Need help in creating a function which removes characters(alphabets) only from end or till a number comes at the right.

For Eg :

select fnStripRightAlpha('ABCD123F') --Should Return 'ABCD123'

select fnStripRightAlpha('PORT123G67KK') --Should Return 'PORT123G67'

select fnStripRightAlpha('123465') --Should Return '123465'

select fnStripRightAlpha('ABCDG') --Should Return ''

I saw functions which remove all alphabets, but they do not solve my purpose as only rightmost characters are to be stripped.

Any Ideas?

like image 902
Abdul Rehman Sayed Avatar asked Aug 01 '26 07:08

Abdul Rehman Sayed


1 Answers

Assuming you only have alphanumeric characters, You can use PATINDEX with STUFF and REVERSE like this.

Query

SELECT
ISNULL(REVERSE(STUFF(REVERSE(col),1,PATINDEX('%[0-9]%',REVERSE(col)) -1,'')),'') as col
FROM
(
    VALUES('ABCD123F'),('PORT123G67KK'),('123465'),('ABCDG')
) as tab(col)

OUTPUT

col
ABCD123
PORT123G67
123465
''
like image 69
ughai Avatar answered Aug 03 '26 19:08

ughai



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!