I have a table tab1
with a column col1
that has compound alpha-then-numeric values, like this:
abc123
xy45
def6
z9
I need to extract the values as separate columns in a query, with the numeric part in a column of integer datatype.
If the two values had a consistent start and end positions, the job could be done with substring()
, as you can see the start of the numeric part varies.
Is there an elegant way to tackle this, or must it be done with a series of unions of each possible start point using a regex match to separate the cases, or rolled up in a huge case statement?
Using LIKE clause Val LIKE '%[A-Z]%', it ensures that string should contain alphanumeric characters. Val LIKE '%[0-9]%', it ensures that string should contain numeric characters. Lets see the output of T-SQL, you can see it returns only alphanumeric string only.
In SQL Server, we can use the ISNUMERIC() function to return numeric values from a column. We can alternatively run a separate query to return all values that contain numeric data.
Yes, it is:
SELECT
@col:=col1 AS col,
@num:=REVERSE(CAST(REVERSE(@col) AS UNSIGNED)) AS num,
SUBSTRING_INDEX(@col, @num, 1) AS word
FROM
tab1
-will work only if your column contain letters and then numbers (like you've described). That's why double REVERSE()
is needed (otherwise CAST()
will have no effect). Check this demo.
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