SQL Query / function to remove alphabets only from end
Need help creating a function that removes characters (alphabets) only from the end or to the number on the right.
For example:
select fnStripRightAlpha('ABCD123F') --Should Return 'ABCD123'
select fnStripRightAlpha('PORT123G67KK') --Should Return 'PORT123G67'
select fnStripRightAlpha('123465') --Should Return '123465'
select fnStripRightAlpha('ABCDG') --Should Return ''
I see functions that remove all alphabets, but they do not solve my purpose as only the right-most characters should be removed.
Any ideas?
+3
source to share
2 answers
Assuming you only have alphanumeric characters, you can use PATINDEX
with STUFF
and REVERSE
as follows.
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
''
+3
source to share